c# - 检查字符串是否包含单词

标签 c# regex arrays string replace

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/

相关文章:

arrays - Swift数组元素地址

c# - XmlSchemaSet 在没有键约束的情况下加载模式

c# - 在控制台窗口不闪烁的情况下启动 conhost.exe

JavaScript 正则表达式替换引用

c# - 如何在数据库的文本字段中存储 byte[] 并检索它

javascript - 按类别排列的产品数组

c# - 从通用模型中获取模型

c# - 从 ListView 排序中排除项目

VSCode 片段中用于删除文件扩展名的正则表达式语句

javascript - 在捕获组前插入 $