Random rnd = new Random(DateTime.Now.Millisecond);
string rt = "tst xtstx xtste tst tst!!";
if (rnd.Next(3) == 0)
{
string[] replaceWords = { "something", "nice" };
rt.Replace("tst", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
if (rnd.Next(3) == 0)
{
string[] replaceWords = { "cool", "crazy" };
rt.Replace("xtste", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
我想以 33% 的概率用数组中的随机单词替换一个单词。问题是,如果我运行此命令,它将替换所有出现的 tst,并且仅替换此出现的位置:
string rt = "tst xtstx xtste tst tst!!";
// /\ /\ /\
有更好的方法来做到这一点,只需替换单词? 我将在我的代码中多次使用相同的想法。
最佳答案
为此,您需要使用正则表达式。
匹配所有tst
单词的正则表达式,您需要使用\btst\b
正则表达式。
要替换所有出现的情况,请使用 Regex.Replace 之一方法。
Here is a something similar example
也不要使用Random(DateTime.Now.Millisecond)
,Random
的默认构造函数具有比这更好的种子。
示例:
static Random rnd = new Random();
static string Replace(string input, string word, params string[] words)
{
return Regex.Replace(input, "\b" + word + "\b", m=>words[rnd.Next(words.Length)]);
}
现在你可以这样使用它:
string rt = "tst xtstx xtste tst tst!!";
if (rnd.Next(3) == 0)
{
rt = Replace(rt, "tst", "something", "nice");
}
if (rnd.Next(3) == 0)
{
rt = Replace(rt, "xtste", "cool", "crazy");
}
关于c# - 检查字符串是否包含单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20977317/