2012-10-02 42 views
0

这是迄今为止的代码,我仍然需要弄清楚如何将添加到字符串的末尾并将nextindex推进到下一个词。读取字符串中的每个单词并在不同行上打印每个单词的函数C

* 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 
+0

这看起来像为家庭作业提供的代码。你有尝试过什么吗?你的问题是什么? –

+0

如何在不改变需要返回的thisindex值的情况下将“\ 0”添加到单词的末尾? –

+1

你熟悉strtok()吗?或者是您不能使用它的作业的一部分? – WhozCraig

回答

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。

相关问题