开发者

Converting space to "+" using C#

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 开发者_Python百科should i do this?


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


String input = "Hello I am";
string output = input.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.


you can try String.Replace

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜