search

Home  >  Q&A  >  body text

c++ - 字符串中删除特定字符的题目中,此处应该用s[j+1]还是s[j]

输入字符串s及待删除的字符ch,将s中所有与ch相同的字符都删除掉,输出删除后得到的新串。以下程序是直接在数组s中进行删除,得到的新串仍然在数组s中。

#include <iostream>
using  namespace  std;

int main( )
{
    char  s[81], ch;
    int k,j;
    cin>>s;
    cin>>ch; //输入待删除的字符(不允许允许为空格符)
    //以下k代表s中每个字符的下标
    //j代表未删除(保留)字符应放在s中新的位置下标
    for(k=j=0;s[k]!='\0';k++)
        if(s[k]!=ch)
        {
            s[j]=s[k];
            __(1)__;
        }
    __(2)__='\0'; //得到的新串末尾要放结束符
    cout<<s<<endl;
    return 0;
}

第一个空填j++;
第二个空填s[j+1]还是s[j];
我认为是s[j],但是网上的答案是s[j+1],如果后者是对的,那么前者在什么情况下出错?

ringa_leeringa_lee2803 days ago1106

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 14:40:44

    should be s[j]
    First look inside the loop. If there is no ch equal to the input, then j==k is always true.
    If ch is encountered, then k will be incremented, but j will not change. That is, if ch is encountered several times, then k will be several times larger than j.
    If there are n chs in the string, then k-j == n should be true when the loop exits. At this time, the position of k is , and it should still be s[j] = s[k], and at this time, s[k] == ', so s[j] == ''.

    reply
    0
  • Cancelreply