在c++中将字符串中的空格替换为%20
Replacing spaces in a string by %20 in C++
#include <iostream>
#include <string>
void removeSpaces(std::string );
int main()
{
std::string inputString;
std::cout<<"Enter the string:"<<std::endl;
std::cin>>inputString;
removeSpaces(inputString);
return 0;
}
void removeSpaces(std::string str)
{
size_t position = 0;
for ( position = str.find(" "); position != std::string::npos; position = str.find(" ",position) )
{
str.replace(position ,1, "%20");
}
std::cout<<str<<std::endl;
}
我看不到任何输出。例如
Enter Input String: a b c
Output = a
怎么了?
std::cin>>inputString;
停在第一个空格处。用途:
std::getline(std::cin, inputString);
。
cin
默认止于空格
把你的输入改为:
// will not work, stops on whitespace
//std::cin>>inputString;
// will work now, will read until n
std::getline(std::cin, inputString);
另一种更好的方法是计算空格的数目,创建长度=旧长度+2*count的新字符串,并开始将字符从旧字符串移动到新字符串,除了空格,将其替换为%20....
实施http://justprogrammng.blogspot.com/2012/06/replace -所有-空间-字符串- - 20. - html
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 在将 unicode 替换为C++字符串中的空格时出现分段错误
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- '+'替换为空格 Curl C++
- 用递增的数字替换字符串中的空格
- 使用std::regex替换前导空格和尾随空格
- 替换字符串中空格的策略
- 如何将 ^M 替换为空格C++
- 用字符串中的空格替换符号
- visual C++-将空格替换为%20
- 程序错误:用"%20"替换空格
- 使用指针将输入中的空格替换为破折号符号
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 将字符串中除空格外的所有字符替换为下划线
- 替换字符串中的空格
- 如何用c++字符串中的空格替换子字符串的所有出现
- 在c++中将字符串中的空格替换为%20
- 为什么用%20程序崩溃替换空格
- 将字符串中的所有空格替换为 '%20' (C++)