visual C++-将空格替换为%20

visual C++ - Replace spaces with %20

本文关键字:替换 空格 C++- visual      更新时间:2023-10-16

我正在寻找一种方法来准备用作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