本文主要是介绍把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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--] = '%';}elsestr[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;
}
运行结果
这篇关于把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!