【问题标题】:Storing separated strings存储分隔的字符串
【发布时间】:2013-01-16 22:28:34
【问题描述】:

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

}

有人有什么建议吗?

【问题讨论】:

    标签: c string stdio words


    【解决方案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;
    }
    

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

    【讨论】:

    • while (input_string[index] != EOF) 似乎是个坏建议。也许您打算针对 '\0' 进行测试?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2023-02-25
    • 2014-12-20
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多