0

そこで、文字列を受け取り、文字列を単語に区切り、区切られた単語を「word1 + word2 + word3 ...」のような形式にするこのプログラムを作成しようとしています。文字列を取得し、文字列を単語に区切ります。しかし、個々の単語を保持してから上記の形式に配置する方法について少し混乱しています。

これまでの私のコードは次のとおりです

#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 に答える