C语言再学习 -- 字符串分割

参看: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循环查询分隔符的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

聚优致成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值