开发者

Special characters in string.Replace

I want to replace special characters in string.

For example this is input text

http\u00253A\u00252F\u00252Fvideo.l3.fbcdn.net\u00252Fcfs-l3-ash4\u00252F351111\u00252F203\u00252F260478023976707_55781.mp4\u00253Foh\u00253D064626d4996116bdcde2d52f9b70e1f0\u002526oe\u00253D4E566C00\u002526l3s\u00253D20110823082632\u002526l3e\u00253D20110825083632\u002526lh\u00253D0dbcb2d22cd4dd5eb10bf

and then I expect this result : http://video.l3.fbcdn.net/cfs-l3-ash4/351111...

But string is not replacing as expected

string[] BadCharacters = { "\\u00253A", "\\u00252F", "\\u00253F" };
string[] GoodCharacters = { ":", "/", "?" };
int i;
for (i = 0; i <= 2; i++)
{
    textBox2.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacter开发者_Python百科s[i]);
}


Your problem is your string gets stomped every iteration through the loop by going back to TextBox1.Text, you need to keep it in a local and keep using the changed value for the next substitution:

var changedText = textBox1.Text;

// always modify and assign to temp, that way we modify previous
for (i = 0; i <= 2; i++)
{
  changedText = changedText.Replace(BadCharacters[i], GoodCharacters[i]);
}

textBox2.Text = changedText;


Try this:

var tmp = textBox1.Text;
for (i = 0; i <= 2; i++)
{
    tmp = tmp.Replace(BadCharacters[i], GoodCharacters[i]);
}

textBox2.Text = tmp;


textBox2.Text will only ever contain one of the substitutions for each loop, so you likely see only the last iteration.

for (i = 0; i <= 2; i++)
{
  textBox1.Text = textBox1.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}

would likely provide the full substituted string desired.


You need to save the updated value of string each time you replace a substring. So save initial value of textBox1 to textBox2 and use it during iteration. In this way, you won't lose your updated string value.

textBox2.Text = textBox1.Text;

for(i = 0; i <= 2; i++)
{
   textBox2.Text = textBox2.Text.Replace(BadCharacters[i], GoodCharacters[i]);
}

Also, by asssigning initial textBox1 value to textBox2 and using it inside your for loop, you save one assigmant statement.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜