【问题标题】:strtok with multiple delimiters具有多个分隔符的 strtok
【发布时间】:2015-12-01 15:41:53
【问题描述】:

我尝试解析如下字符串:

"12 13 14   16"

数组中的 5 个数字。

我用strtok(string_above, " "),但是strtok()会把这三个空白字符当作一个。我能做些什么来预防它?

【问题讨论】:

  • 不使用 strtok。 strtok 会将一系列分隔符视为单个分隔符。
  • 改用strchr()。阅读strchr(3)。您将对标记化有很多控制权。
  • 预期的结果是什么?带有{12, 13, 14, 0, 16}的数组?
  • 所以真的是三个空格。第一个和最后一个是分隔符,中间的一个是零?这不是一个理智的格式。如果字符串连续只包含两个空格怎么办?
  • 即使你可以这样做,我也不推荐。使用空白作为分隔符并同时用作空白不是一件好事,因为它非常模棱两可。

标签: c strtok


【解决方案1】:

我确实喜欢这样做,这可能是您需要的。我没有对它进行广泛的测试,但它通过了一个简单的测试。

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

int
main(void)
{
    char string[] = "12 13 14   16";
    char *current;
    char *next;
    int done;
    current = string;
    done = 0;
    while (done == 0)
    {
        next = strchr(current, ' ');
        if (next == NULL)
            next = strchr(current, '\0');
        // If there are no more tokens, current[0] will be 
        // equal to 0 and (end == current) too
        done = (current[0] == '\0');
        if ((next != current) && (done == 0))
        {
            // We nul terminate it (replace the delimiter with nul)
            // so now, current is the token.
            next[0] = '\0';
            // Display the token
            printf("--%s--\n", current);
            // Restore the character
            next[0] = ' ';
            // Advance to the next characeter (for the next strchr())
            current = next + 1;
        }
        else if (*next++ == ' ') // If the next character is a space, 
        {                        // it's a delimiter
            int spaces;
            int count;

            // Count the number of spaces to see 
            // if the space is a delimiter or a token
            spaces = 1;
            // Count the number of tokens
            count = 1;
            // While the current character is a space, we seek for a non-space
            while (isspace((unsigned char) *next) != 0)
            {
                next++;
                if (spaces % 2 == 0) // If it's an even space (it's a token)
                    count += 1;
                spaces++;
            }
            // If the spaces variable is not even 
            // there was no delimiter for the last
            // token consider this an input error
            if (spaces % 2 != 0)
                return -1;
            // Print the blanks as 0's
            for (int i = 0 ; i < count ; ++i)
                printf("--0--\n");
            // Advance to the next characeter (for the next strchr())
            current = next;
        }
    }
    return 0;
}

【讨论】:

  • 这非常接近我的需要,但我认为会有一个非常简单的方法来解决它。非常感谢,谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多