C语言实现按分隔符来截取字符串

本文介绍如何使用C语言中的strtok()函数按指定分隔符拆分字符串,并提供了一个具体的示例程序,展示了如何将一个由逗号分隔的字符串逐个元素提取并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:我们的系统通过Socket网络通讯往linux服务器上发送数据,服务器上接收的数据格式是以逗号隔开的字符串。我们需要将这个字符串按逗号作为分隔符来截取。

解决方法:使用C语言中的strtok()函数实现

代码实现(下面代码的功能是将字符串"now , is the time for all , good men to come to the , aid of their country"以逗号作为分隔符来截取,并将截取出的字符串打印出来):

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "now , is the time for all , good men to come to the , aid of their country";
    char delims[] = ",";
    char *result = NULL;
    result = strtok( str, delims );
    while( result != NULL ) {
    printf( "result is \"%s\"\n", result );
    result = strtok( NULL, delims );
    }
}
运行结果如下:



进一步:封装成实现按分隔符截取字符串的函数

#include <stdio.h>  
#include <string.h>  
void split(char str[],char delims[])
{
    char *result = NULL; 
    result = strtok( str, delims );  
    while( result != NULL ) {  
    printf( "result is \"%s\"\n", result );  
    result = strtok( NULL, delims );  
    }  
}
int main()  
{  
    char str[] = "now , is the time for all , good men to come to the , aid of their country";  
    char delims[] = ",";  
	split(str,delims);
}  


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值