赞
踩
目录
字符串查找分为:在字符串中查找单个字符,在字符串中查找多个字符,在字符串中查找子串。
查找单个字符使用strchr与strrchr;
查找多个字符使用strpbrk;
查找子串使用strstr;
strspn和strcspn,逐个检查两个字符串是否相同
和其它字符串处理函数一样,使用这些函数时需要包含头文件 <string.h>
strchr与strrchr函数声明如下:
- char *strchr(const char *s, int c);
- char *strrchr(const char *s, intc);
这两个函数都是从字符串s中查找字符c,如果找到字符c就返回,返回值指向这个位置,如果没有找到字符c,返回NULL。
strchr与strrchr函数的不同在于:strchr从左向右查找字符,strrchr从右向左查找字符。
使用示例,在字符串str中查找字符c并打印结果:
- char *str = "When we let go of something.it opens up a little space to grow.";
- int c = 'g';
- char *ppos = strchr(str,c);
- char *ppos1 = strrchr(str,c);
-
- printf("str\t\t= %s\n",str);
- printf("strchr ret\t= %s\n",ppos);
- printf("strrchr ret\t= %s\n",ppos1);
输出结果如下:
str = When we let go of something.it opens up a little space to grow.
strchr ret = go of something.it opens up a little space to grow.
strrchr ret = grow.
strpbrk函数声明:
char *strpbrk(const char *s1, const char *s2);
strpbrk函数在源字符串s1中按从前往后的顺序找出最先含有字符串s2中任一字符的位置并返回,不包含'\0',如果找不到返回空指针。函数定义如下:
- char *strpbrk(const char *s1, const char *s2)
- {
- while( *s1 != '\0')
- {
- const char *a = s2;
- while(*a != 0)
- {
- if(*a++ == *s1)
- return (char*)s1;
- ++s1;
- }
- }
- }
使用示例:
- char *str = "When we let go of something.it opens up a little space to grow.";
- char* str2 = "met";
- char *ppos2 = strpbrk(str,str2);
- printf("str\t\t= %s\n",str);
- printf("strpbrk ret\t= %s\n",ppos2);
输出结果:
str = When we let go of something.it opens up a little space to grow.
strpbrk ret = en we let go of something.it opens up a little space to grow.
strstr函数声明:
char *strstr(const char *str1, const char *str2);
strstr函数在字符串str1中从左到右查找str2,str1连续包含str2中的所有字符时,返回str1中第一次出现str2的位置的指针,如果没有找到,返回NULL。
使用示例:
- char *str = "When we let go of something.it opens up a little space to grow.";
- char* str2 = "met";
- char *ppos3 = strstr(str,str2);
- printf("str\t\t= %s\n",str);
- printf("strstr ret\t= %s\n",ppos3);
输出结果:
str = When we let go of something.it opens up a little space to grow.
strstr ret = mething.it opens up a little space to grow.
strspn和strcspn函数声明:
- size_t strspn(const char *s,const char *accept);
- size_t strcspn(const char *s,cosnt char *reject);
strspn从字符串s的第一个字符开始,逐个检查与字符串accept中的字符是否不相同,如果不相同,停止检查,返回以字符串s开头连续包含accept内的字符的数目;
strcspn从字符串s的第一个字符开始,逐个检查与reject中的字符是否相同,如果相等,停止检查,返回以字符串s开头连续不含字符串reject内的字符数目,
使用示例:
- char *str = "When we let go of something.it opens up a little space to grow.";
- char *str3 = "bdjk";
- size_t pos1 = strspn(str,str3);
- size_t pos2 = strcspn(str,str3);
-
- printf("%s = %d\n",str3,pos1);
- printf("%s = %d\n",str3,pos2);
-
- char *str4 = "When";
-
- pos1 = strspn(str,str4);
- pos2 = strcspn(str,str4);
-
- printf("%s = %d\n",str4,pos1);
- printf("%s = %d\n",str4,pos2);
输出结果:
str = When we let go of something.it opens up a little space to grow.
bdjk = 0
bdjk = 63
When = 4
When = 0
使用strspn和strcspn时需要注意:
使用strspn时,当第一个字符不相同或者字符串s不包含accept中的任一字符时,返回0;
使用strcspn时,当第一个字符相同时,返回0;当字符串s不包含accept的任一字符时,返回字符串长度。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。