大家好,欢迎来到IT知识分享网。
问题描述:我们的系统通过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);
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/22847.html