所以我正在尝试编写一个带字符串的程序,将字符串分隔成单词并将分隔的单词放入“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," ");
}
}
有没有人有任何建议?
答案 0 :(得分: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;
}
如果您还想要其他内容,请编辑问题。