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;
}
运行结果