李晓亮的博客

导航

C语言中的字符串操作函数

1.strtok
功能:得到字符串s1中首次出现s2中的字符前的子字符串
原型:char *strtok(char *s1, const char *s2)
参数:该函数将s1中首次出现s2中字符的位置置为NULL,因此会破坏s1字符串。该函数一般用于分解s1字符串为用特定分隔符分隔的多个字符串,s2一般设置为s1中的分隔字符,比如空格,逗号等,例如将一条自然英文语句分解为单词。
返回:字符串s1中首次出现s2中的字符前的子字符串指针
2.strcspn
功能:从参数s1字符串的开头计算连续的字符,而这些字符都完全不在参数s2所指的字符串中。简单地说,若strcspn()返回的数值为n,则代表字符串s1开头连续有n个字符都不含字符串s2内的字符。
原型:int strcspn(const char *s1, const char *s2)
参数:
返回:返回字符串s1开头连续不含字符串s2内的字符数目。

范例
#include <string.h>
main()
{
char *str="Linux was first developed for 386/486-based pcs.";
printf("%d\n",strcspn(str," "));
printf("%d\n",strcspn(str,"/-"));
printf("%d\n",strcspn(str,"1234567890"));
}
执行
5 /*只计算到“ ”的出现,所以返回“Linux”的长度*/
33 /*计算到出现“/”或“-”,所以返回到“6”的长度*/
30 /* 计算到出现数字字符为止,所以返回“3”出现前的长度*/

3.strstr
功能:得到在s1中第一次包含s2字符串的位置
原型:char *strstr(const char *s1, const char *s2)
参数:
返回:在s1中第一次包含s2字符串的位置指针
范例

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char *s="书中自有颜如玉";
  char *l="颜如玉";
  char *p;
 

  p=strstr(s,l);
  if(p!=NULL)
     printf("%s",p);
  else
     printf("Not Found!");

  system("PAUSE"); 
  return 0;
}

执行
颜如玉
注:测试环境Dev C++ 4.9.9.2

4.strpbrk
功能:得到s1中首次出现的也是s2中字符的位置指针
原型:char *strpbrk(const char *s1, const char *s2)
参数:
返回:位置指针
5.strspn
功能:得到s1中第一个同时也不是s2中任意字符的字符位置
原型:int strspn(const char *s1, const char *s2)
参数:
返回:位置指针
6.
功能:
原型:
参数:
返回:

posted on 2010-11-19 18:17  LeeXiaoLiang  阅读(187)  评论(0)    收藏  举报