假设我有一个字符串 "file1.h: file2.c,file3.cpp"
,我想将其拆分为 "file1.h"
和 "file2.c,file3.cpp"
- 使用 :
(:
和空格)作为分隔符。我该怎么做?
我在没有帮助的情况下尝试了这段代码:
int main(int argc, char *argv[]) {
char str[] = "file1.h: file2.c,file3.cpp";
char name[100];
char depends[100];
sscanf(str, "%s: %s", name, depends);
printf("Name: %s\n", name);
printf("Deps: %s\n", depends);
}
我得到的输出是:
Name: file1.h:
Deps:
最佳答案
您似乎需要的是strtok()
。在 man page 中阅读相关内容。相关引用来自 C11
,第 §7.24.5.8 章
A sequence of calls to the
strtok
function breaks the string pointed to bys1
into a sequence of tokens, each of which is delimited by a character from the string pointed to bys2
. [...]
就您而言,您可以使用类似的分隔符
char * delim = ": "; //combination of : and a space
去完成工作吧。
另外要提一下,
- 对于
strtok()
,输入需要是可修改的(在您的情况下) - 它实际上破坏了提供给它的输入,如果您稍后需要实际的输入,请保留一份副本。
关于c - 使用多个字符作为分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38899126/