0

所以我正在尝试编写这个程序,它接受一个字符串,将字符串分隔成单词并将分隔的单词放入“word1 + word2 + word3 ...”之类的格式我已经编写了一个获取字符串的C程序和将字符串分成单词。但是我对如何保留每个单词然后将其以上述格式放置有点困惑。

到目前为止,这是我的代码

#include <stdio.h>
#include <string.h>
int main()
{
 int wordCount = 0;
 char realString[200];
 char testString[200];
 char * nextWordPtr;

 printf("Input string\n");
 gets(realString);


 strcpy(testString,realString);

 nextWordPtr = strtok(testString," "); // split using space as divider

 while (nextWordPtr != NULL) {

 printf("word%d %s\n",wordCount,nextWordPtr);

 wordCount++;

 nextWordPtr = strtok(NULL," ");
}

}

有没有人有什么建议?

4

1 回答 1

1

我真的不明白你想要什么?如果您只想输出这样的字符串:' word0+word1+...etc ',您可以使用此代码来完成此操作:

#include <stdio.h>
#include <stdlib.h>

#define INPUT_STRING_LEN                128

int main(int argc, char **argv)
{
        char input_string[INPUT_STRING_LEN];
        char *out_string;
        int index;

        /* Get user input */
        fgets(input_string, INPUT_STRING_LEN, stdin);

        out_string = (char *) malloc((INPUT_STRING_LEN + 1) * sizeof(char));
        /* Loop through input string and replace space with '+' */
        index = 0;
        while (input_string[index] != '\0')
        {
                if (input_string[index] == ' ')
                        out_string[index] = '+';
                else
                        out_string[index] = input_string[index];

                index++;
        }

        /* We got this out string */
        fprintf(stdout, "We got this out string :\n--->\n%s<---\n", out_string);

        /* Free the allocated memory */
        free(out_string);

        return 0;
}

如果您想要其他内容,请编辑问题。

于 2013-01-17T00:06:12.190 回答