输入字符串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],如果后者是对的,那么前者在什么情况下出错?
should be s[j]
First look inside the loop. If there is no
ch
equal to the input, thenj==k
is always true.If
ch
is encountered, thenk
will be incremented, butj
will not change. That is, ifch
is encountered several times, thenk
will be several times larger thanj
.If there are
n
ch
s in the string, thenk-j == n
should be true when the loop exits. At this time, the position ofk
is