请考虑以下示例。
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."
我该怎么做?
答案 0 :(得分:23)
以下是你如何使用正则表达式来处理任何单词边界:
Regex r = new Regex(@"\bThe\b");
s = r.Replace(s, "@@");
答案 1 :(得分:4)
我在上面做了一个评论,询问为什么标题被更改为假设使用正则表达式。
我个人尝试不使用正则表达式,因为它很慢。 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);
答案 2 :(得分:3)
s = s.Replace(“The”,“@@”);
答案 3 :(得分:0)
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] + " ");
}
}
}