c++ 求助~~ 达人来帮帮小弟

来源:百度知道 编辑:UC知道 时间:2024/09/23 23:20:25
Write a function that inputs a string and converts the string such that the modified string contains only single spaces between different words and doesn’t start or end with spaces.

Eg. string s = “ this is super weird ! ”;
removeSpaces(s);
cout<<s<<endl; //outputs “this is super weird !

#include <iostream>
#include <string>
using namespace std;

string RemoveSpaces(string& str){
string s;
for(string::iterator it=str.begin();it!=str.end();it++){
if(*it!=' '){
s+=*it;
if(*(it+1)==' ')
s+=' ';
}
}
return s;
}

int main(void){
string s=" this is super weird ! ";
cout<<"Before Remove:"<<endl;
cout<<s<<endl;
cout<<"After Remove:"<<endl;
cout<<RemoveSpaces(s)<<endl;
return 0;
}

简单的方法就是判断一下前后字符可能出现的情况,把符合条件的输出就是,参考代码:
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
int i;
string s = " this is super weird ! ";
for(i = 0; i < s.length()-1;i++)
{