0

到目前为止,这是我的代码,我仍然需要弄清楚如何添加'\0'到字符串的末尾并将 nextindex 推进到下一个单词的开头。

 * inputs: str - the string,
 * if str is NULL, return the index of the next word in the string
 * AND place a '\0' at the end of that word.
 */
int nextword(char *str)
{
    // create two static variables - these stay around across calls
    static char *s;
    static int nextindex;
    int thisindex;
    // reset the static variables
    if (str != NULL)
    {
        s = str;
        thisindex = 0;
        // TODO:  advance this index past any leading spaces
        while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' '                )
          thisindex++;  

    }
    else
    {
        // set the return value to be the nextindex
        thisindex = nextindex;
    }
    // if we aren't done with the string...
    if (thisindex != -1)
    {
        // TODO: two things
        // 1: place a '\0' after the current word
        // 2: advance nextindex to the beginning
        // of the next word

    }
    return thisindex;
}

我想要以下代码

char *str = "Welcome everybody! Today is a beautiful day\t\n";
int i = nextword(str);
while(i != -1)
{
    printf("%s\n",&(str[i]));
    i = nextword(NULL);
}

输出

Welcome 
everybody!
Today 
is
a 
beautiful
day
4

1 回答 1

0

当您的代码中已经包含所需的操作时,我真的不明白您为什么要寻求帮助:

    // TODO: two things
    // 1: place a '\0' after the current word
    // 2: advance nextindex to the beginning
    // of the next word

所以让我们分解一下。

  1. 您需要搜索您的字符串,直到找到一个空格。您已经有一个执行相反操作的循环。您将单词后面的字符替换为'\0'. 小心不要跑过字符串的末尾。

  2. 我认为数字 2 不需要解释,只是说您需要确保如果您发现自己位于输入字符串的末尾(在上面的数字 1 中),则设置nextindex为 -1。

于 2012-10-02T04:42:12.447 回答