【问题标题】:Using strtok to separate words and remove , and ()使用 strtok 分隔单词并删除 , 和 ()
【发布时间】:2018-12-24 15:58:34
【问题描述】:

我的程序应该使用一个短语并分隔所有单词并将它们打印在没有任何',','('或')'的新行上。这是我的代码。到目前为止,它似乎正在工作,但如果可能的话,我想改进它。另外,我不知道这是否是一个问题,但它似乎从一个单词中删除了 '(' 和 ')' 但不是两者都删除了。因此,“(test”或“test)”将按预期仅输出“test”,但“(test)”输出“test)”。不确定这是否可以。无论如何我该如何改进呢?

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

void function(char *string)
{
    const char delim[2] = " ";
    char *token;
    int n, i, j;

    token = strtok(string, delim);
    while (token != NULL) {
        n = strlen(token);
        if (strstr(token, ",")) {
            for (i = j = 0; i < n; i++) {
                if (token[i] != ',')
                    token[j++] = token[i];
            }
            token[j] = '\0';
        }else if (strstr(token, "(")) {
            for (i = j = 0; i < n; i++) {
                if (token[i] != '(')
                    token[j++] = token[i];
            }
            token[j] = '\0';
        } else if (strstr(token, ")")) {
            for (i = j = 0; i < n; i++) {
                if (token[i] != ')')
                    token[j++] = token[i];
            }
            token[j] = '\0';
        }

        printf("%s\n", token);
        token = strtok(NULL, delim);
    }
}

int main(void)
{
    char test[80] = "The next appointment is on the 7.1.2019, 10:00 a.m., in HS 1 (Building C)";
    char input[80];

    gets(input);
    function(test);
    function(input);
    return 0;
}

【问题讨论】:

  • 只有在没有找到( 时才检查)。这没有任何意义。您应该检查每个字符,只要找到任何字符。

标签: c arrays string strtok


【解决方案1】:

你可以像下面的代码那样做:

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

void function(char *string)
{
    const char delim[10] = " ,()";
    char *token = strtok(string, delim);
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, delim);
    }
}

int main(void)
{
    char test[80] = "The next appointment is on the 7.1.2019, 10:00 a.m., in HS 1 (Building C)";

    function(test);

    return 0;
}

解释:

每次调用 strtok() 都会返回一个指向以 null 结尾的字符串的指针 包含下一个令牌。该字符串不包括 分隔字节。如果找不到更多标记,则 strtok() 返回 NULL。

见http://man7.org/linux/man-pages/man3/strtok.3.html

【讨论】:

  • 你能解释一下 delim 是如何使用的吗?所以它的功能是删除每个符号,然后结果是令牌?
  • @saty,正如云斌所说,阅读手册页了解详细说明
  • @Saty yes, strtok() remove all char in delim
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
相关资源
最近更新 更多