1

I am looking for a way to prepare a string for use as a URL.

The basics of the code is you type in what you are looking for and it opens a browser with what you typed in. I am learning C++, so this is a learning program. And please be as specific as possible for I am new to C++.

Here is what I am trying to do:

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());

But I am trying to replace all the spaces the user enter with a '%20'. I have found one method this way but it only works with one letter at a time, and I am needing to do it with a full string and not an array of chars. Here is the method I have tried:

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());

Thanks for your help!

alexander7567
  • 665
  • 13
  • 35
  • What you're actually trying to do is escape all special characters in a string. Space is not the only character illegal in URLs. – Wug Jul 18 '12 at 03:59
  • For basic "find and replace" on strings, see [this question](http://stackoverflow.com/q/3418231/501250). But you should really consider using a third-party library to properly URI-encode the string instead. – cdhowie Jul 18 '12 at 04:01
  • @wug You are correct about that. But this is simply a learning program and I can only take it one step at a time. I will be the only one using this.. – alexander7567 Jul 18 '12 at 04:01

3 Answers3

5

If you have Visual Studio 2010 or later you should be able to use regular expressions to search/replace:

std::regex space("[[:space:]]");
s_input = std::regex_replace(s_input, space, "%20");

Edit: How to use the six-argument version of 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");

The string s_output now contains the changed string.

You might have to change the replacement string to std::string("%20").

As you see I have only five arguments, that's because the sixth should have a default value.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

std::replace is only able to replace single elements (chars in this case) with single elements. You are trying to replace a single element with three. You will need a special function to do that. Boost has one, called replace_all, you can use it like this:

boost::replace_all(s_input, " ", "%20");
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

If you google: C++ UrlEncode, you will find many hits. Here's one:

http://www.zedwood.com/article/111/cpp-urlencode-function

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69