参看:DSP学习 – Visual Studio 操作
参看:C语言再学习 – C 标准库 - string.h
参看:C语言再学习 – 字符串和字符串函数
参看:STM32开发 – 进制与字符串间的转换
一、C 库函数 - strtok()
描述
C 库函数 char *strtok(char *str, const char *delim) 分解字符串 str 为一组字符串,delim 为分隔符。
参数
str – 要被分解成一组小字符串的字符串。
delim – 包含分隔符的 C 字符串。
返回值
该函数返回被分解的第一个子字符串,如果没有可检索的字符串,则返回一个空指针。
示例
#include <stdio.h>
#include <string.h>
void main(void)
{
char str[80] = "This is , hello world ,, test";
char *temp = str;
char s[2] = ",";
char *res;
res = strtok(temp, s);
while(res != NULL)
{
printf("%s\n", res);
res = strtok(NULL, s);
}
return;
}
结果:
This is
hello world
test
我们首先使用 strtok() 函数将字符串 str 分割成单词,并指定逗号作为分隔符。然后,我们使用一个循环遍历分割后的子字符串,直到没有更多的子字符串可分割。
需要注意的是,strtok() 函数会修改原始字符串,将分隔符替换为空字符 (‘\0’)。因此,如果需要保留原始字符串,可以创建一个副本进行分割。
二、问题
本来是要查看字符串strtok库函数的功能实现函数的。
在内核源码/kernel/lib/string.c
意思应该是用 strsep 函数取代 strtok 函数。
上面字符串 str[80] = “This is , hello world , test”;
忽略了两个逗号之间没有数据的情况。
三、C 库函数 - strsep()
函数原型
char* strsep(char** stringp, const char* delim)
参数
stringp: 要被分割的字符串地址,函数执行后该元素被更改,总是只想要被分割的字符串;
delim: 分割符;
返回值
函数返回分割后的第一个字符串。函数执行的过程,是在 *stringp 中查找分割符,并将其替换为“\0”,返回分割出的第一个字符串指针 (NULL 表示到达字符串尾),并更新 *stringp 指向下一个字符串。
示例
#include <stdio.h>
#include <string.h>
void main(void)
{
char str[80] = "This is , hello world ,, test";
char *temp = str;
char s[2] = ",";
char *res;
while(res = strsep(&temp, s))
{
printf("%s\n", res);
}
return;
}
结果:
This is
hello world
test
第一个参数需要传入字符串指针的指针,第二个参数传入分隔符的指针。调用的时候每次循环调用的时候都会返回下一个字符串的指针没有的时候返回NULL,与strtok的调用区别是,他每次调用第一个参数都传入的是要分割的字符串指针的指针,而strtok第一次是指针,后面串入的是NULL。
三、C 语言实现
#include <stdio.h>
#include <string.h>
void main(void)
{
char str[80] = "This is , hello world ,, test";
char s = ',';
int i = 0, start = 0, end = 0;
char temp[80] = {0};
for(i = 0;i < strlen(str)+1;i++)
{
if((str[i] == s) || (i == strlen(str)))
{
end = i - start;
memcpy(temp, str+start, end);
printf("%s\n", temp);
memset(temp, '\0', sizeof(temp));
start = i+1;
}
}
return;
}
结果:
This is
hello world
test
采用for循环查询分隔符的方式。