我很困惑创建一个函数,该函数将打印一个字符串并要求用户输入两个数字,然后函数将相互替换这些单词数。 我添加了下面的图片作为示例。 enter image description here
这是我的作业,我已经创建了其他 3 个函数,但并没有真正理解这个。 有人可以帮助我如何将单词转换为数字,然后将这些单词数量相互替换。
这是我的程序,它可以将字符串分解为单词,但我如何替换单词的位置。
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
for(i=0;i<=(strlen(str1));i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if(str1[i]==' '||str1[i]=='\0')
{
newString[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
最佳答案
在我看来,到目前为止你做得很好(你的代码无法处理逗号,但你可以稍后添加)。因此,我们假设您的 newString
实际上包含各个单词。
因此,下一步是根据 newString
中的各个单词构造一个新字符串 str2。当您这样做时,您可以简单地交换感兴趣的两个单词。要构建新字符串,strcat
函数可能会有所帮助。
下面的代码并不完全正确,但它可能会给您一些继续作业的想法:
int lowest_index_to_swap = some_number
int highest_index_to_swap = some_higher_number
char str2[100] = "";
for (i=0; i<number_of_words_found; ++i)
{
if (i == lowest_index_to_swap)
strcat(str2, newString[highest_index_to_swap];
else if (i == highest_index_to_swap)
strcat(str2, newString[lowest_index_to_swap];
else
strcat(str2, newString[i];
strcat(str2, " ";
}
关于C程序函数将一个单词替换为另一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51768640/