一、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/zh-hant/n/238505.html
微信掃一掃
支付寶掃一掃