请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路: 从字符串尾部开始复制和替换。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
char* s_str = new char[100];
getline(cin, s);
s_str = const_cast<char*>(s.data());//将string类型转换成char*类型保存
cout<<"结果:"<<s_str<<endl;
//
int oldstrLen = strlen(s_str);
int blankNum = 0;
for (int i = 0; i<oldstrLen; i++){
if (s_str[i] == ' '){
blankNum++;//计算空格数量
}
}
for (oldstrLen - 1; oldstrLen>=0;oldstrLen--){
if (s_str[oldstrLen] != ' '){
s_str[oldstrLen+2*blankNum] = s_str[oldstrLen];
}//不是空格就复制
else{
blankNum--;
s_str[oldstrLen + 2 * blankNum] = '%';
s_str[oldstrLen + 2 * blankNum + 1] = '2';
s_str[oldstrLen + 2 * blankNum + 2] = '0';
}
}
cout<<"结果:"<<s_str<<endl;
return 0;
}
补充:字符串的输入
1.单个字符,getchar()
#include<iostream>
using namespace std;
main ()
{
char ch;
ch=getchar(); //不能写成getchar(ch);
cout<<ch<<endl;
}
输入:jkljkljkl
输出:j
//getchar()是C语言的函数,C++也可以兼容,但是尽量不用或少用;
2. 字符串(不包含空格)
#include<iostream>
#include<string>
using namespace std;
int main()
{
//单个字符串输入,遇到空格 tab 结束
char ch[20];
cin>>ch;
cout<<"out:"<<ch<<endl;
return 0;
}
3.字符串,可以输出空格(getline(),gets())
#include<iostream>
#include<string>
using namespace std;
int main()
{
char ch[20];
gets(ch); //不能写成ch=gets();
cout<<ch<<endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout<<str<<endl;
return 0;
}