在剑指offer中看到将字符串中的空格进行替换,文章使用的是字符数组进行的操作,在这里我进行了尝试改进,使用string类对象,将剑指offer一书中编写的代码进行了改进,仅供参考^_^_^_^_^_^_^_^
从屏幕输入中获取用户输入,将用户输入的字符串中的空格使用“%20”字符串代替。
#include <iostream>
#include <string>
using namespace std;
void replaceBlank(string str)
{
//判断字符串是否为空
int orgLen=str.length();
if(orgLen==0)
return;
//计算新字符串的长度
int numOfBlank=0;
for(int i=0;i<orgLen;i++)
{
if(str[i]==' ')
numOfBlank++;
}
int newLen=orgLen+numOfBlank*2;
str.append(numOfBlank*2,' '); //由于在对原字符串基础上进行替换,字符串长度变长,所以在字符串末尾append要空字符进行扩展。
//对字符串从后向前替换空格
int indexOfOrg=orgLen-1; //indexOfOrg指向原字符串的最后一个字符的位置
int indexOfNew=newLen-1; //indexOfNew指向扩展后字符串的最后一个字符的位置
while(indexOfOrg>=0 && indexOfNew>indexOfOrg)
{
if(str[indexOfOrg]==' ')
{
str[indexOfNew--]='0';
str[indexOfNew--]='2';
str[indexOfNew--]='%';
}
else
{
str[indexOfNew--]=str[indexOfOrg];
}
indexOfOrg--;
}
cout << str << endl;
}
int main()
{
string str;
while(getline(cin,str))
replaceBlank(str);
return 0;
}
以上代码在进行编写时需要注意一下问题:
(1)string类对象的长度不同于字符数组,通过string.length()获得的字符串长度就是实际的字符串的长度,末尾并不需要考虑 ‘\0’ 字符(这里我还不明白,是编译器对字符串进行了优化,还是string类对象最后就没有这个字符);
(2)由于在原字符串基础上进行替换,字符串长度变长,所以在原字符串末尾append要空字符进行扩展。以防止后面打印字符串时产生截断;
对上述代码进行测试:
[In]:what the fuck. //输入空格在字符串中间
[Out]:what%20the%20fuck.
[In]: fuck. //输入空格在字符串头部
[Out]:%20%20fuck.
[In]:what the fuck . //输入空格在字符串尾部,且是连续空格
[Out]:what%20the%20fuck%20%20%20.
[In]: //输入一个空格
[Out]:%20
[In]:fuck. //无空格输入
[Out]:fuck.