Question

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?

Was it helpful?

Solution

String input = "Hello I am";
string output = input.Replace(" ", "+");

OTHER TIPS

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

you can try String.Replace

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

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.

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(' ', '+');
string s = "Hello I am";
s = s.Replace(" ", "+");

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top