c - 存储分隔的字符串

标签 c string stdio words

所以我试图编写这个程序,它接受一个字符串,将字符串分隔成单词,并将分隔的单词放入“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," ");
}

}

有人有什么建议吗?

最佳答案

不太明白你到底想要什么?如果您只想输出这样的字符串:'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;
}

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

关于c - 存储分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14369092/

相关文章:

c - 从线程返回 "string"

c 打印包含结构的树

r - 在 data.frame 中查找字符串

java - 从控制台读取并使用 stdio 写入文件

c - P 线程 - 从不同大小的整数转换为指针

c - 在 C 中是否有调用堆栈转储的函数?

ios - 无法将类型 "String"的值分配给 swift 类型 "UILabel"

c++ - 使用后缀数组和 LCP(-LR) 实现字符串模式匹配

c - 从文本文件读取后,结果显示不正确

c - 如何停止输入字符卡在缓冲区中? C