C - 拆分字符串

标签 c string split

在给定分隔符的情况下,C 中是否有任何预定义函数可以拆分字符串?假设我有一个字符串:

"Command:Context"

现在,我想将“Command”和“Context”存储到一个二维字符数组中

char ch[2][10]; 

或者两个不同的变量

char ch1[10], ch2[10];

我试过使用循环,效果很好。我只是好奇是否已经存在这样的功能,我不想重新发明轮子。请给出一个清晰的例子,非常感谢!

最佳答案

您可以使用 strtok

Online Demo :

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

int main ()
{
    char str[] ="Command:Context";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str,":");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, ":");
    }
    return 0;
}

输出:

Splitting string "Command:Context" into tokens:
Command
Context

关于C - 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7884807/

相关文章:

arrays - strsplit : undefined function for input type 'char'

python - 如何拆分 Python 列表的每个第 N 个元素

python - 字符串替换列 pandas

string - VBscript 中是否有 "\n"等效项?

java - 使用 Java 将嵌套 Markdown 转换为 HTML

multithreading - Apache Camel拆分与线程池并行运行,为什么?

c - 多线程程序额外运行while循环次数

c - 如何使用 (a*X)/b 公式中的两个可能更大的数字重新缩放 int

用c语言将文本编码成莫尔斯码

c - 与 GLFW MinGW 的链接问题