用另一个词替换句子中的一个词

Replacing a word in a sentence with a another word

我正在研究这个问题,但其中有一些奇怪的错误。问题出在 "Replace" 函数中。我已经在下面的代码中评论了这个问题。

我做了三个动态字符数组(sentence,word1,word2),用cin.getline输入。我想要做的是如果 :

句子="I like pizza",

word1 = "like",以及

word2 = "hate"

那我要句="I hate pizza"。

此外,这是我第一次使用堆栈溢出,所以如果此线程有任何问题,请告诉我。非常感谢您的帮助。

 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] != '[=10=]' || found == true; i++)
        {
            lisw = 0;

            //Problem is down here. The loop doesn't terminate when encountering a
            //space character. When i used static_cast code to check the ASCII 
            //values only junk values were output. If i just cout<<s; then there is
            //no problem but doing it here causes some weird logical errors.
            for (int j = i; s[j] != ' '; j++)
            {
                lisw++;
                cout << static_cast<int>(s[j]);
            }

            found = true;

            for (int j = i; j < lisw; j++)
            {
                if (s[j] != w1[j])
                {
                    found = false;
                }

            }

            if (found == true)
            {
                for (int j = i; j < lisw; j++)
                {
                    s[j] = w2[j];
                }
            }

            i = i + lisw;
        }
    }

好的,感谢评论,我找到了解决方案。我将在下面复制更正后的代码。可以在评论中看到更正。

 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]!='[=10=]' && found!=true;i++) //Replaced || with &&.
        {
            lisw=0;

            for (int j=i;s[j]!=' '&& s[j]!='[=10=]';j++)//added: && s[j]!='[=10=]' 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;
        }
    }