4

I want to convert a string to an url and, instead of a space, it needs a "+" between the keywords.

For instance:

"Hello I am"

to:

"Hello+I+am"

How should i do this?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
klopske
  • 83
  • 1
  • 5

7 Answers7

11

For URLs, I strongly suggest to use Server.UrlEncode (in ASP.NET) or Uri.EscapeUriString (everywhere else) instead of String.Replace.

Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288
5
String input = "Hello I am";
string output = input.Replace(" ", "+");
Katalonis
  • 691
  • 2
  • 6
  • 16
  • hanks for the help, but I only need to convert spaces to pluses IF the string contains more than one word. How can i build in this condition? – klopske Nov 15 '10 at 10:24
4

You can use string.Replace:

"Hello I am".Replace(' ', '+');

If you want to url encode a string (so not only spaces are taken care of), use Uri.EscapeUriString:

Uri.EscapeUriString("Hello I am");

From MSDN:

By default, the EscapeUriString method converts all characters, except RFC 2396 unreserved characters, to their hexadecimal representation. If International Resource Identifiers (IRIs) or Internationalized Domain Name (IDN) parsing is enabled, the EscapeUriString method converts all characters, except for RFC 3986 unreserved characters, to their hexadecimal representation. All Unicode characters are converted to UTF-8 format before being escaped.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Note that using `EscapeUriString` will produce *"Hello%20I%20am"*, not *"Hello+I+am"*. This shouldn't really be a problem though in any sane system. – LukeH Nov 15 '10 at 09:59
3

you can try String.Replace

"Hello I am".Replace(' ','+');

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
2

Assuming that you only want to replace spaces with pluses, and not do full URL-encoding, then you can use the built-in Replace method:

string withSpaces = "Hello I am";

string withPluses = withSpaces.Replace(' ', '+');
LukeH
  • 263,068
  • 57
  • 365
  • 409
0
string s = "Hello I am";
s = s.Replace(" ", "+");
Itay Karo
  • 17,924
  • 4
  • 40
  • 58
0

To answer the 'convert a string to an url' part of your question (you shouldn't manually convert the string if you want a correct URL):

string url = "http://www.baseUrl.com/search?q=" + HttpUtility.UrlEncode("Hello I am");

You call Url Encode on each parameter to correctly encode the values.

Rox
  • 1,985
  • 12
  • 19