检查字符串是否包含一个单词

时间:2022-04-13 04:20:23
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)]);
}

I want to replace a word with a random one from a array with a 33% chance. The problem is if I run this it will replace all occurrences of tst, and only to replace this occurrences:

我想用一个概率为33%的随机数组替换一个单词。问题是,如果我运行它,它将替换所有tst的出现,并且只替换这些出现:

string rt = "tst xtstx xtste tst tst!!";
//           /\              /\  /\

There is a better way to do this only replacing the words ? I will use the same idea multiple times in my code.

有更好的方法来代替单词吗?我将在代码中多次使用相同的思想。

4 个解决方案

#1


3  

You need to use regular expressions for this.

您需要为此使用正则表达式。

Regex that match all tst words, you need to use \btst\b regex.

要匹配所有tst单词,需要使用\btst\b Regex。

To replace all occurances use one of Regex.Replace methods.

用正则表达式替换所有发生的事件。替代方法。

Here is a something similar example

这里有一个类似的例子

Also don't use Random(DateTime.Now.Millisecond), default constructor of Random has better seed than this.

也不要使用Random(datetime . now .毫秒),Random的默认构造函数有更好的种子。

Example:

例子:

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)]);
}

now you can use it as this:

现在你可以这样使用它:

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");
}

#2


1  

you can use \b to denote a word boundry with a regular expression.

您可以使用\b来表示一个带有正则表达式的单词boundry。

Also - don't forget to assign back to the original string!

另外——不要忘记将它赋值回原来的字符串!

Random rnd = new Random();

string rt = "tst xtstx xtste tst tst!!";

if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "something", "nice" };
    rt = Regex.Replace(rt, @"\btst\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "cool", "crazy" };
    rt = Regex.Replace(rt, @"\bxtste\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}

#3


1  

Do this. Use Regex.Replace and /b to use only the word.

这样做。使用正则表达式。替换和/b,只使用单词。

Random rnd = new Random(DateTime.Now.Millisecond);

string rt = "tst xtstx xtste tst tst!!";

if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "something", "nice" };
    rt = Regex.Replace(rt, @"\tst\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "cool", "crazy" };
    rt = Regex.Replace(rt, @"\xtste\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}

method to do some of the repeated work.

方法做一些重复的工作。

public string ReplaceRandom(string[] words, string wordToReplace, string inputString)
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    inputString = Regex.Replace(inputString, @"\b" + wordToReplace + @"\b", words[rnd.Next(words.Length - 1)]);
    return inputString;
}

Or if you wanted to use an extension method to kind of stick with the String.Replace line of thinking you could do. Call it with rt.ReplaceWithRandom(replaceWords, "tst");

或者如果你想使用扩展方法来固定字符串。改变你的想法。用rt.ReplaceWithRandom(替换词,tst)调用它;

public static string ReplaceWithRandom(this string inputString, string[] words, string wordToReplace)
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    inputString = Regex.Replace(inputString, @"\b" + wordToReplace + @"\b", words[rnd.Next(words.Length - 1)]);
}

#4


0  

It seems to me like you want a different random word for each match. Here's a class that will do this for you.

在我看来,每一场比赛你都想要一个不同的随机单词。这是一个为你做这些的类。

public class RandomStringReplacer
{
    // no need to seed this w/ the current time, the default constructor does that already
    private readonly Random _random = new Random();

    private readonly Regex _regex;

    private readonly string[] _replacementStrings;

    public RandomStringReplacer(string pattern, params string[] replacementStrings)
    {
        _regex = new Regex(pattern);
        _replacementStrings = replacementStrings.ToArray();
    }

    // each time we get a replacement string, a randomly selected one is chosen
    private string RandomReplacement
    {
        get { return _replacementStrings[_random.Next(_replacementStrings.Length)]; }
    }

    public string Replace(string text)
    {
        var random = new Random();
        var result = text;

        // get the matches as a stack, because we want to replace backwards so that indexes still match the correct spot in the string
        var matches = new Stack<Match>(_regex.Matches(text).OfType<Match>());
        while (matches.Count > 0)
        {
            var match = matches.Pop();
            // each match has a 1/3 chance to be replaced
            if (random.Next(3) == 0)
            {
                result = result.Remove(match.Index, match.Length).Insert(match.Index, RandomReplacement);
            }
        }
        return result;
    }
}

Usage:

用法:

var replacements = new[]{"foo", "bar", "FUBAR"};
var pattern = @"(tst)|(xtste)";
var replacer = new RandomStringReplacer(pattern, replacements);

var text = "tst xtstx xtste tst tst!!";
replacer.Replace(text).Dump();

#1


3  

You need to use regular expressions for this.

您需要为此使用正则表达式。

Regex that match all tst words, you need to use \btst\b regex.

要匹配所有tst单词,需要使用\btst\b Regex。

To replace all occurances use one of Regex.Replace methods.

用正则表达式替换所有发生的事件。替代方法。

Here is a something similar example

这里有一个类似的例子

Also don't use Random(DateTime.Now.Millisecond), default constructor of Random has better seed than this.

也不要使用Random(datetime . now .毫秒),Random的默认构造函数有更好的种子。

Example:

例子:

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)]);
}

now you can use it as this:

现在你可以这样使用它:

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");
}

#2


1  

you can use \b to denote a word boundry with a regular expression.

您可以使用\b来表示一个带有正则表达式的单词boundry。

Also - don't forget to assign back to the original string!

另外——不要忘记将它赋值回原来的字符串!

Random rnd = new Random();

string rt = "tst xtstx xtste tst tst!!";

if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "something", "nice" };
    rt = Regex.Replace(rt, @"\btst\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "cool", "crazy" };
    rt = Regex.Replace(rt, @"\bxtste\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}

#3


1  

Do this. Use Regex.Replace and /b to use only the word.

这样做。使用正则表达式。替换和/b,只使用单词。

Random rnd = new Random(DateTime.Now.Millisecond);

string rt = "tst xtstx xtste tst tst!!";

if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "something", "nice" };
    rt = Regex.Replace(rt, @"\tst\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}
if (rnd.Next(3) == 0)
{
    string[] replaceWords = { "cool", "crazy" };
    rt = Regex.Replace(rt, @"\xtste\b", replaceWords[rnd.Next(replaceWords.Length - 1)]);
}

method to do some of the repeated work.

方法做一些重复的工作。

public string ReplaceRandom(string[] words, string wordToReplace, string inputString)
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    inputString = Regex.Replace(inputString, @"\b" + wordToReplace + @"\b", words[rnd.Next(words.Length - 1)]);
    return inputString;
}

Or if you wanted to use an extension method to kind of stick with the String.Replace line of thinking you could do. Call it with rt.ReplaceWithRandom(replaceWords, "tst");

或者如果你想使用扩展方法来固定字符串。改变你的想法。用rt.ReplaceWithRandom(替换词,tst)调用它;

public static string ReplaceWithRandom(this string inputString, string[] words, string wordToReplace)
{
    Random rnd = new Random(DateTime.Now.Millisecond);
    inputString = Regex.Replace(inputString, @"\b" + wordToReplace + @"\b", words[rnd.Next(words.Length - 1)]);
}

#4


0  

It seems to me like you want a different random word for each match. Here's a class that will do this for you.

在我看来,每一场比赛你都想要一个不同的随机单词。这是一个为你做这些的类。

public class RandomStringReplacer
{
    // no need to seed this w/ the current time, the default constructor does that already
    private readonly Random _random = new Random();

    private readonly Regex _regex;

    private readonly string[] _replacementStrings;

    public RandomStringReplacer(string pattern, params string[] replacementStrings)
    {
        _regex = new Regex(pattern);
        _replacementStrings = replacementStrings.ToArray();
    }

    // each time we get a replacement string, a randomly selected one is chosen
    private string RandomReplacement
    {
        get { return _replacementStrings[_random.Next(_replacementStrings.Length)]; }
    }

    public string Replace(string text)
    {
        var random = new Random();
        var result = text;

        // get the matches as a stack, because we want to replace backwards so that indexes still match the correct spot in the string
        var matches = new Stack<Match>(_regex.Matches(text).OfType<Match>());
        while (matches.Count > 0)
        {
            var match = matches.Pop();
            // each match has a 1/3 chance to be replaced
            if (random.Next(3) == 0)
            {
                result = result.Remove(match.Index, match.Length).Insert(match.Index, RandomReplacement);
            }
        }
        return result;
    }
}

Usage:

用法:

var replacements = new[]{"foo", "bar", "FUBAR"};
var pattern = @"(tst)|(xtste)";
var replacer = new RandomStringReplacer(pattern, replacements);

var text = "tst xtstx xtste tst tst!!";
replacer.Replace(text).Dump();