how to replce '=' with " = " insted of "==" in c#
-
Tuesday, March 13, 2012 5:30 PM
Hi
My Problem is that i want to replace "=" with " = " from string but my string also contains "==" operator i just only want to replace"=" not "==".How it is possible.Plz help
Thanks
All Replies
-
Tuesday, March 13, 2012 5:36 PMAre you talking about a string replacement or are you talking about in your code?
It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.
-
Tuesday, March 13, 2012 6:31 PM
Hmm, maybe this might help?
string text = "The = must be replaced, when == must not be."; string newText = ""; foreach (string word in text.Split(new string[]{" "}, StringSplitOptions.None)) { if (word.Equals("=")) newText += string.Format(" {0} ", word); else newText += string.Format("{0} ", word); } MessageBox.Show(newText);
Mitja
- Marked As Answer by Verstyleshoaib Friday, March 16, 2012 7:47 PM
-
Wednesday, March 14, 2012 1:07 PM
How about :
string value = 'if ( z == y ) ' ; // Basic replace value = value.Replace( "=", " = " ); // Clean-up anything we've wrongly converted value = value.Replace( " = = ", " == " );
Regards, Phill W.
- Proposed As Answer by Padma Lahore Wednesday, March 14, 2012 1:08 PM
- Unproposed As Answer by Padma Lahore Wednesday, March 14, 2012 1:44 PM
-
Wednesday, March 14, 2012 1:44 PM
Or you use RegularExpressions!
String input = "The=must be replaced, when == must not be."; String pattern = @"\b=\b"; String replacement = " = "; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern); String result = rgx.Replace(input, replacement);
Trimmed version:
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"\b=\b"); String result = rgx.Replace("The=must be replaced, when == must not be.", " = ");
- Edited by Padma Lahore Wednesday, March 14, 2012 1:54 PM
-
Thursday, March 15, 2012 8:50 AM
Ah, this RegularExpression is even better for your problem:
Long Version:
String input = "The=must be replaced, when == must not be."; String pattern = @"=(?=.*==)"; String replacement = " = "; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern); String result = rgx.Replace(input, replacement);
Short Version:
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"=(?=.*==)"); String result = rgx.Replace("The=must be replaced, when == must not be.", " = ");
- Proposed As Answer by Padma Lahore Thursday, March 15, 2012 8:51 AM
- Marked As Answer by Bob Wu-MTMicrosoft Contingent Staff, Moderator Monday, March 19, 2012 1:54 AM


