开发者

string replace in c# [duplicate]

This question already has an answer here: Closed 11 years ago. 开发者_StackOverflow中文版

Possible Duplicate:

String replace not working

I have a stirng like:

string url = "abc=$abc";
url.Replace("$abc", "123");

Then what I expected it url = "abc=123". But actually, after runing above code, the result is still is "abc=$abc", not "abc=123".

How to resolve this problem?


You want

url = url.Replace("$abc", "123");

Replace() returns a new instance of string with the replacement operation done. It (and all other string operations) does not change the original string instance.


Strings are immutable, this means that you create a new string instead of changing the original:

url = url.Replace("$abc", "123");


Strings are immutable, meaning it won't change in place. Try assigning the result of replace to another string variable.

string url = "abc=$abc";
string newUrl = url.Replace("$abc", "123");


try

url = url.Replace("$abc", "123");

String.Replace Method

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.


You need to set the original string, or a new string, equal to the value returned from String.Replace. Using your example, do this:

string url = "abc=$abc";
url = url.Replace("$abc", "123");


url = url.Replace("$abc", "123");

.Replace returns a NEW string - you must assign that back to the original string if you want to change it.


url = url.Replace("$abc", "123");


Replace returns a string. So you need to change your second statement to:

url = url.Replace("$abc", "123");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜