C语言 存储分隔的字符串



所以我试着写这个程序,它接受一个字符串,将字符串分隔成单词,并将分隔的单词放入像"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 stringn");
 gets(realString);

 strcpy(testString,realString);
 nextWordPtr = strtok(testString," "); // split using space as divider
 while (nextWordPtr != NULL) {
 printf("word%d %sn",wordCount,nextWordPtr);
 wordCount++;
 nextWordPtr = strtok(NULL," ");
}
}

有人有什么建议吗?

我真的不明白你想要什么?如果您只是想像这样输出字符串:'word0+word1+…等',你可以使用下面的代码来完成:

#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] != '')
        {
                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;
}

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

最新更新