C语言 将字符串拆分为标记并将它们保存在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15472299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:45:18  来源:igfitidea点击:

Split string into tokens and save them in an array

csplitstrtok

提问by Syeda Amna Ahmed

How to split a string into an tokens and then save them in an array?

如何将字符串拆分为标记然后将它们保存在数组中?

Specifically, I have a string "abc/qwe/jkh". I want to separate "/", and then save the tokens into an array.

具体来说,我有一个 string "abc/qwe/jkh"。我想将"/",然后将令牌保存到数组中。

Output will be such that

输出将是这样的

array[0] = "abc"
array[1] = "qwe"
array[2] = "jkh"

please help me

请帮我

回答by rlib

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

int main ()
{
    char buf[] ="abc/qwe/ccd";
    int i = 0;
    char *p = strtok (buf, "/");
    char *array[3];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok (NULL, "/");
    }

    for (i = 0; i < 3; ++i) 
        printf("%s\n", array[i]);

    return 0;
}

回答by MOHAMED

You can use strtok()

您可以使用 strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

while(array[i]!=NULL)
{
   array[++i] = strtok(NULL,"/");
}