c - 使用多个字符作为分隔符分割字符串

标签 c string split

假设我有一个字符串 "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 by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. [...]

就您而言,您可以使用类似的分隔符

  char * delim = ": "; //combination of : and a space

去完成工作吧。

另外要提一下,

  • 对于strtok(),输入需要是可修改的(在您的情况下)
  • 它实际上破坏了提供给它的输入,如果您稍后需要实际的输入,请保留一份副本。

关于c - 使用多个字符作为分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38899126/

相关文章:

c - 在 Arm 程序集中使用 C 中声明的全局变量

r - 按 ID 选择随机样本

video - 如何使用 ffmpeg 获得相等的分段时间?

arrays - 将数组拆分为 n、m、o 组或更多组

c - 我需要生成一组97到122之间的随机数

c - 即使所有管道都已关闭,程序仍想获取输入

c++ - 如何获取另一个应用程序的所有窗口的句柄

正则表达式在多个定界符之前拆分字符串

r - 如何获取字符串中出现频率最高的字符?

android - 比较android中的两个波斯字符串