visual C++-将空格替换为%20
visual C++ - Replace spaces with %20
我正在寻找一种方法来准备用作URL的字符串。
代码的基础是你输入你想要的内容,它会用你输入的内容打开浏览器。我正在学习C++,所以这是一个学习程序。请尽可能具体,因为我是C++的新手。
以下是我要做的:
cin >> s_input;
transform(s_input.begin(), s_input.end(), s_input.begin(), tolower);
s_input = "start http://website.com/" + s_input + "/0/7/0";
system(s_input.c_str());
但我正在尝试用"%20"替换用户输入的所有空格。我用这种方式找到了一个方法,但它一次只能处理一个字母,而且我需要用一个完整的字符串而不是一个字符数组。这是我尝试过的方法:
cin >> s_input;
transform(s_input.begin(), s_input.end(), s_input.begin(), tolower);
using std::string;
using std::cout;
using std::endl;
using std::replace;
replace(s_input.begin(), s_input.end(), ' ', '%20');
s_input = "start http://website.com/" + s_input + "/0/7/0";
system(s_input.c_str());
谢谢你的帮助!
如果您有Visual Studio 2010或更高版本,您应该能够使用正则表达式来搜索/替换:
std::regex space("[[:space:]]");
s_input = std::regex_replace(s_input, space, "%20");
编辑:如何使用std::regex_replace
:的六参数版本
std::regex space("[[:space:]]");
std::string s_output;
std::regex_replace(s_output.begin(), s_input.begin(), s_input.end(), space, "%20");
字符串s_output
现在包含更改后的字符串。
您可能需要将替换字符串更改为std::string("%20")
。
正如你所看到的,我只有五个参数,这是因为第六个应该有一个默认值。
std::replace
只能用单个元素替换单个元素(在本例中为字符)。您正试图用三个元素替换单个元素。你将需要一个特殊的功能来做到这一点。Boost有一个,叫做replace_all
,你可以这样使用它:
boost::replace_all(s_input, " ", "%20");
如果你在谷歌上搜索:C++UrlEncode,你会发现很多点击。这里有一个:
http://www.zedwood.com/article/111/cpp-urlencode-function
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 在将 unicode 替换为C++字符串中的空格时出现分段错误
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- '+'替换为空格 Curl C++
- 用递增的数字替换字符串中的空格
- 使用std::regex替换前导空格和尾随空格
- 替换字符串中空格的策略
- 如何将 ^M 替换为空格C++
- 用字符串中的空格替换符号
- visual C++-将空格替换为%20
- 程序错误:用"%20"替换空格
- 使用指针将输入中的空格替换为破折号符号
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 将空白字符替换为 %20 的字符串,忽略所有尾随空格
- 将字符串中除空格外的所有字符替换为下划线
- 替换字符串中的空格
- 如何用c++字符串中的空格替换子字符串的所有出现
- 在c++中将字符串中的空格替换为%20
- 为什么用%20程序崩溃替换空格
- 将字符串中的所有空格替换为 '%20' (C++)