如何从C++程序中删除多个空格并用一个空格代替?
我尝试的是:-
#include<iostream>
using namespace std;
int main()
{
char str[80],i, j;
cin>>str;
for(i=0; i!='\0'; i++)
{
if(str[i]=' '&&str[i]==str[i+1])
{
for(j=i+1; str[j]!='\0'; j++)
str[j-1]=str[j];
}
}
cout<<str;
}
Run Code Online (Sandbox Code Playgroud)
cin每当遇到空格时就会截断字符串。要读取整行,请使用getline(). 我也建议使用std::string.
std::string str;
std::getline(std::cin,str);
for(i=str.size()-1; i >= 0; i-- )
{
if(str[i]==' '&&str[i]==str[i-1]) //added equal sign
{
str.erase( str.begin() + i );
}
}
Run Code Online (Sandbox Code Playgroud)
循环从末尾开始迭代,以便
1.str.size()复杂性被消除。
2.在擦除操作中引入了一点效率(如果有很多空格)。