我有一个包含两个名字和一个逗号的字符串,我怎么能将它们分开并将它们写成单独的字符串。
示例
char *line="John Smith,Jane Smith";
我正在考虑使用sscanf函数。
sscanf(line,"%s,%s",str1,str2);
我该怎么办?
注意:我可以将逗号更改为空格字符。
答案 0 :(得分:8)
我正在考虑使用sscanf函数。
甚至不要考虑它。
char line[] = "John Smith,Jane Smith";
char *comma = strchr(line, ',');
*comma = 0;
char *firstName = line;
char *secondName = comma + 1;
答案 1 :(得分:-1)
以下是使用strtok
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
// Your string.
char *line = "John Smith,10,Jane Smith";
// Let's work with a copy of your string.
char *line_copy = malloc(1 + strlen(line));
strcpy(line_copy, line);
// Get the first person.
char *pointer = strtok(line_copy, ",");
char *first = malloc(1 + strlen(pointer));
strcpy(first, pointer);
// Skip the number.
strtok(NULL, ",");
// Get the second person.
pointer = strtok(NULL, ",");
char *second = malloc(1 + strlen(pointer));
strcpy(second, pointer);
// Print.
printf("%s\n%s", first, second);
return 0;
}