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
這看起來像爲家庭作業提供的代碼。你有嘗試過什麼嗎?你的問題是什麼? –
如何在不改變需要返回的thisindex值的情況下將「\ 0」添加到單詞的末尾? –
你熟悉strtok()嗎?或者是您不能使用它的作業的一部分? – WhozCraig