一、strsep函数的用法
strsep函数可以用来分解字符串,将字符串按照指定的分隔符分成若干个子字符串,并返回其中一个子字符串。在使用strsep函数时需要注意以下几点:
1. 函数使用后会改变原来字符串的内容,所以如果涉及到原字符串的使用,需要备份。
2. 不能传入const类型的字符串,因为分隔符的位置需要函数内部更改。
3. 如果字符串结尾没有分隔符,函数返回最后一个子字符串的地址,否则返回空指针。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; char *sep = ","; while ((p = strsep(&str, sep)) != NULL) { printf("%s\n", p); } return 0; }
二、strsep函数如果没找到
如果分隔符不存在,strsep函数返回NULL,一般需要通过判断返回值是否为空指针来判断分解是否结束。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; char *sep = "|"; while ((p = strsep(&str, sep)) != NULL) { printf("%s\n", p); } if (str == NULL) { printf("分解结束!\n"); } return 0; }
三、strsep函数头文件
strsep函数的头文件是string.h,需要在使用之前引入该头文件。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; char *sep = ","; while ((p = strsep(&str, sep)) != NULL) { printf("%s\n", p); } return 0; }
四、strsep函数和strtok
strsep函数和strtok函数功能类似,都可以用来分解字符串。比较不同的是strsep函数的分隔符是一个字符串,而strtok函数的分隔符是一个字符。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; char *sep = ","; p = strtok(str, sep); while (p != NULL) { printf("%s\n", p); p = strtok(NULL, sep); } return 0; }
五、strstr函数
strstr函数可以用来查找字符串中是否包含指定的子字符串。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; p = strstr(str, "world"); if (p != NULL) { printf("找到了子字符串:%s\n", p); } else { printf("没有找到子字符串!\n"); } return 0; }
六、strstr函数用法
strstr函数除了可以判断字符串中是否包含子字符串外,还可以返回包含子字符串的起始地址。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; p = strstr(str, "world"); if (p != NULL) { printf("子字符串的起始地址:%p\n", p); printf("子字符串:%s\n", p); } else { printf("没有找到子字符串!\n"); } return 0; }
七、strsplit函数
strsplit函数是一种使用方便的字符串分解函数,可以将字符串分解为多个子字符串。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; int count = 0; while ((p = strsep(&str, ",")) != NULL) { printf("子字符串:%s\n", p); count++; } printf("一共分解成了%d个子字符串!\n", count); return 0; }
八、strstream函数
strstream函数是一种流式的字符串分解函数,可以将字符串流式地分解为多个子字符串。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; int count = 0; char *rest = str; while ((p = strsep(&rest, ",")) != NULL) { printf("子字符串:%s\n", p); count++; } printf("一共分解成了%d个子字符串!\n", count); return 0; }
九、strstr函数c
strstr函数c是C标准库中的函数,可以用于查找字符串中是否包含指定的子字符串。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char *p; p = strstr(str, "world"); if (p != NULL) { printf("找到了子字符串:%s\n", p); } else { printf("没有找到子字符串!\n"); } return 0; }
十、strsub函数用法
strsub函数可以用来截取指定字符串中的一段子字符串。
#include <stdio.h> #include <string.h> int main() { char str[] = "hello,world"; char sub[100]; strncpy(sub, str + 6, 5); sub[5] = '\0'; printf("子字符串:%s\n", sub); return 0; }
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/238505.html