c - 用C中的任何空格分隔字符串

标签 c string token whitespace tokenize

我有一个字符串,例如“123 789”,我想要的结果是将此输出的字符串分开:

123 
789

我已经创建了完成此操作的代码,通过查找空格来分隔字符串。

我需要帮助来编辑我的代码,以通过回车符、换行符、垂直制表符、自由格式制表符或一系列空格来分隔字符串。基本上,任何空白字符。目前,如果除了一个空格以外的任何东西分隔字符串的不同部分,我的代码就会中断。

这是我的代码,目前由一个空格分隔:

int counter = 0; //counter used in loop
int index = test->current_index; //holds the current index of my string, it's initially 0
char *string = test->myString; //holds the whole string

char token_buffer = string[index];

//before loop: index = 0, counter = 0

while(test->current_index <= test->end_index)
{
    counter = 0;
    token_buffer = string[counter+index];
    while(token_buffer != ' ' && (index+counter)<=test->end_index)
    {
        counter++;
        token_buffer = string[index+counter];
    }

    char *output_token = malloc(counter+1);
    strncpy(output_token,string+index,counter);
    printf("%s \n", output_token);
    TestProcessing(output_token); //sends each token to be processed further

    //update information
    counter++;   
    test->current_index += counter;
    index += counter;
    return 0;
}

最佳答案

要像这样定义一个 util 函数,

int is_delimiter(char c)
{
    char delimiters[] = {'\0','\n','\r',' '};//customize to expand  
    for(int i = 0; i < sizeof(delimiters); i++){
         if(delimiters[i] == c)
            return 1;
    }
    return 0;
}

然后,

while(!is_delimiter(token_buffer) && (index+counter)<=test->end_index)

关于c - 用C中的任何空格分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31106440/

相关文章:

char * 打印出奇怪的字符

python - 查找已连接的 token

c - 在 C 中通过命令行传递标点符号

android - 使用 ID 的字符串形式从 strings.xml 获取字符串

python - 运算符优先级对字符串的工作方式与对数字的工作方式相同吗?

javascript - 如果两个值都会动态更改,则用变量替换某些字符串的一部分 - Javascript

token - 将 token 保存在 YAML 文件 *private/secure* (Coveralls.io)

c - memcpy 的奇怪结果

c - 使用 Fgets 读取 cpp 文件的所有行

c - 如何将数组拆分为特定大小