如何用逗号分割字符串,可选地后跟没有正则表达式的空格?

时间:2013-09-09 10:54:33

标签: c parsing

我需要这个简单的分割

Item one, Item2,  Item no. 3,Item 4
>
Item one
Item2
Item no.3
Item 4
  • 我知道我可以在scanf中使用%*[, ]格式来忽略逗号和空格,但这不准确:分隔符应该只是一个逗号,后面可以跟空格。
  • 我想我也不能使用strtok,因为单独的空间不是分隔符。

我真的需要正则表达式,还是有任何有效的简短编码方式?

2 个答案:

答案 0 :(得分:6)

如下:

char inputStr[] = "Item one, Item2,  Item no. 3,Item 4";
char* buffer;

buffer = strtok (inputStr, ",");

while (buffer) {
    printf ("%s\n", buffer);          // process token
    buffer = strtok (NULL, ",");
    while (buffer && *buffer == '\040')
        buffer++;
}

输出:

Item one
Item2
Item no. 3
Item 4

答案 1 :(得分:0)

您可以单步执行字符串查找,或者0x00并替换任何一个0x00,然后跳过任何空格以查找下一个字符串的开头。正则表达式更容易。