您的位置:首页 > 其它

把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”

2018-02-14 14:21 344 查看
c++代码

#include<iostream>
using namespace std;

void replaceBlank(char *str)
{
if (str == NULL)
return;

int originalLength = 0, blank = 0, i = 0;
int newLength,originalIndex,newIndex;
while (str[i] != '\0')
{
originalLength++;
if (str[i] == ' ')
blank++;
i++;
}
newLength = originalLength + blank * 2;
originalIndex = originalLength;
newIndex = newLength;
while (originalIndex > 0 && newLength > originalIndex)
{
if (str[originalIndex] == ' ')
{
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
}
else
str[newIndex--] = str[originalIndex];
originalIndex--;
}
}

int main()
{
char str[30] = "I love my hometown";
cout << "输入的字符串为" << endl;
cout << str<<endl;

replaceBlank(str);
cout << "替换空格后字符串为" << endl << str<<endl;

system("pause");
return 0;
}

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐