如何替换C#中的特定单词?
请考虑以下示例。
string s = "The man is old. Them is not bad.";
如果我使用
s = s.Replace("The", "@@");
然后它返回"@@ man is old. @@m is not bad."
但我希望输出为"@@ man is old. Them is not bad."
我怎样才能做到这一点?
以下是如何使用正则表达式来处理任何单词边界:
Regex r = new Regex(@"\bThe\b"); s = r.Replace(s, "@@");
我在上面做了一个评论,询问为什么标题被改为假设使用正则表达式。
我个人试图不使用正则表达式,因为它很慢。 Regex非常适合复杂的字符串模式,但是如果字符串替换很简单并且你需要一些性能,我会试着找到一种不使用Regex的方法。
扔了一个测试。 使用Regex和字符串方法运行一百万次替换。
正则表达式需要26.5秒才能完成,字符串方法需要8秒才能完成。
//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);
s = s.Replace(“The”,“@@”);
C#console应用程序
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] + " "); } } }