How can I replace a specific word with C #?

Consider the following example.

string s = "The man is old. Them is not bad."; 

If i use

 s = s.Replace("The", "@@"); 

Then it returns "@@ man is old. @@m is not bad."
But I want the result to be "@@ man is old. Them is not bad."

How can i do this?

+6
string c # regex replace
source share
4 answers

Here you can use a regular expression that will process any word boundaries:

 Regex r = new Regex(@"\bThe\b"); s = r.Replace(s, "@@"); 
+23
source share

I made a comment above, asking why the name was changed to suggest that Regex should have been used.

I personally try not to use Regex because it is slow. Regex is great for complex string patterns, but if string replacements are simple and you need some kind of performance, I will try to find a way without using Regex.

Made a test. Launch a million replicas using the Regex and string methods.

Regex took 26.5 seconds to execute string methods for 8 seconds .

  //Using Regex. Regex r = new Regex(@"\b[Tt]he\b"); System.Diagnostics.Stopwatch stp = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { string str = "The man is old. The is the Good. Them is the bad."; str = r.Replace(str, "@@"); } stp.Stop(); Console.WriteLine(stp.Elapsed); //Using String Methods. stp = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { string str = "The man is old. The is the Good. Them is the bad."; //Remove the The if the stirng starts with The. if (str.StartsWith("The ")) { str = str.Remove(0, "The ".Length); str = str.Insert(0, "@@ "); } //Remove references The and the. We can probably //assume a sentence will not end in the. str = str.Replace(" The ", " @@ "); str = str.Replace(" the ", " @@ "); } stp.Stop(); Console.WriteLine(stp.Elapsed); 
+4
source share

s = s.Replace ("The", "@@");

+3
source share

C # Console Application

 static void Main(string[] args) { Console.Write("Please input your comment: "); string str = Console.ReadLine(); string[] str2 = str.Split(' '); replaceStringWithString(str2); Console.ReadLine(); } public static void replaceStringWithString(string[] word) { string[] strArry1 = new string[] { "good", "bad", "hate" }; string[] strArry2 = new string[] { "g**d", "b*d", "h**e" }; for (int j = 0; j < strArry1.Count(); j++) { for (int i = 0; i < word.Count(); i++) { if (word[i] == strArry1[j]) { word[i] = strArry2[j]; } Console.Write(word[i] + " "); } } } 
0
source share