How do I replace multiple occurrences of substrings using a custom c# function?
I wrote the code below to replace strings but it seemed like there is something wrong w开发者_开发技巧ith the code. It couldn't replace multiple times. It only can replace the first occurrence. It suppose to replace all occurrences.
//Do not use System.Security.SecurityElement.Escape. I am writing this code for multiple .NET versions.
public string UnescapeXML(string s)
{
if (string.IsNullOrEmpty(s)) return s;
return s.Replace("&", "&").Replace("'", "'").Replace(""", "\"").Replace(">", ">").Replace("<", "<");
}
protected void Page_Load(object sender, EventArgs e)
{
string TestData="TestData&amp;amp;";
Response.Write("using function====>>>>" + UnescapeXML(TestData));
Response.Write("\n\n<BR>Not using function====>>>>" + TestData.Replace("&", ""));
}
Your function is operating correctly, assuming you want a one-pass (per substring) solution.
Your testDate is missing &
characters before amp;
Change to:
string TestData="TestData&&&";
From:
string TestData="TestData&amp;amp;";
What is a one-pass (per substring) solution?
- Each unique substring1 occurrence is changed.
- Then, each unique substring2 occurrence is changed.
- ...
- Then, each unique substringN occurrence is changed.
Recursive Alternative
A recursive solution would involve the following:
After one-single substring replacement, you call the function again
If no replacements occured, return the string
public string ReplaceStuff(string MyStr) { //Attempt to replace 1 substring if ( ReplacementOccurred ){ return ReplaceStuff(ModifiedString); }else{ return MyStr; } }
What do you get with Recursion?
- Well, given an input string:
&amp;
, it would first be changed to&
, then the next level of recursion would change it to&
. - I honestly don't think the author wants the recursive solution, but I could see how passersby might.
Looks like the HttpUtility class will be the best choise in that case.
精彩评论