好的,多亏了这些评论,我找到了一个解决方案。我将复制下面更正的代码。可以在评论中看到更正。
void Replace(char* s,char* w1, char* w2)
{
int lisw = 0; //lisw = letters in single word
bool found =false;
for (int i=0;s[i]!='\0' && found!=true;i++) //Replaced || with &&.
{
lisw=0;
for (int j=i;s[j]!=' '&& s[j]!='\0';j++)//added: && s[j]!='\0' so the loop terminates because otherwise it kept finding "spaces" since the character array was of a larger size to accommodate any sentence.
{
lisw++;
}
found=true;
int k=0;
for (int j=i;j<lisw+i;j++) //loop goes until lisw+i instead of lisw
{
if (s[j]!=w1[k])
{
found=false;
}
k++;
}
k=0;
if (found==true)
{
for (int j=i;j<lisw+i;j++)//same as above.
{
s[j]=w2[k];
k++;
}
}
i=i+lisw;
}
}