剑指offer--替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%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;
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值