您的位置:首页 > 编程语言 > C语言/C++

C语言 strtok 字符串分割

2017-04-07 18:24 423 查看

C语言 strtok 字符串分割

参考:

C++ 字符串分割方法 实现splithttp://blog.csdn.net/u012005313/article/details/46483057

使用函数
strtok
可实现
C
语言环境下的字符串分割

百度百科:strtok

cstring:strtok

函数:

char * strtok ( char * str, const char * delimiters );


参数:

str:待分割的字符串

delimiters:分隔符(字符串中每个字符均为分隔符

功能:分割字符串

例程:

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

int main(int argc, char* argv[]) {
char str[] = "- This, a sample string.";
char * pch;
printf("Splitting string \"%s\" into tokens:\n", str);
pch = strtok(str, " ,.-");
while (pch != NULL)
{
printf("%s\n", pch);
pch = strtok(NULL, " ,.-");
}

printf("str: %s\n", str);

system("pause");
return 0;
}


结果:



问题1:经过分割后,字符串
str
不再和原先一致


封装了一个函数:

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

#define IN
#define OUT

typedef struct split {
char info[1024];
int num;
struct split *next;
}SplitInfo;

void GetSplitString(IN char* str, IN char* delim, OUT SplitInfo* splitInfo)
{
int n = 0;
char* next = NULL;
SplitInfo* top = splitInfo;

char arr[1024];
strcpy(arr, str);

next = strtok(arr, delim);
if (next == NULL) {
splitInfo->num = 0;
splitInfo->next = NULL;

return;
}

SplitInfo* in = (SplitInfo*)malloc(sizeof(SplitInfo));
strcpy(in->info, next);
in->next = NULL;
top->next = in;
top = in;
n++;

while (next = strtok(NULL, delim))
{
SplitInfo* te = (SplitInfo*)malloc(sizeof(SplitInfo));
strcpy(te->info, next);
te->next = NULL;
top->next = te;
top = te;
n++;
}

splitInfo->num = n;
}

void SplitFree(SplitInfo* splitInfo) {
SplitInfo* top = splitInfo->next;
while (top) {
SplitInfo* next = top->next;
free(top);
top = next;
}

splitInfo->next = NULL;
splitInfo->num = 0;
}

int main(int argc, char* argv[]) {
char str[] = "- This, a sample string.";
//char * pch;
printf("Splitting string \"%s\" into tokens:\n", str);
//pch = strtok(str, " ,.-");
//while (pch != NULL)
//{
//  printf("%s\n", pch);
//  pch = strtok(NULL, " ,.-");
//}

SplitInfo splitInfo;
splitInfo.next = NULL;
GetSplitString(str, " ,.-", &splitInfo);

SplitInfo* top = &splitInfo;
for (int i = 0; i < splitInfo.num; i++) {
top = top->next;
printf("%s\n", top->info);
}

SplitFree(&splitInfo);

printf("str: %s\n", str);

// ----

char str2[] = "Hello World";
GetSplitString(str2, "Hello World", &splitInfo);

top = &splitInfo;
for (int i = 0; i < splitInfo.num; i++) {
top = top->next;
printf("%s\n", top->info);
}

SplitFree(&splitInfo);

printf("str2: %s\n", str2);

system("pause");
return 0;
}


结果:



问题2:输入参数
str
应该为数组而非字符串?

参考:C语言中strtok函数进行分割字符串!

但是在封装后的函数中输入字符串同样可以运行,这里还没太搞懂字符串和数组的区别,以及实参和形参的转换,等待以后搞懂

问题3:函数
strtok
是非线程安全的函数?

Linux
环境下,可以使用函数
strtok_r
来代替

百度百科:strtok_r
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: