簡體   English   中英

如何用不同的數字替換每個字符串匹配?

[英]How can I replace each string match with a different number?

我正在嘗試更換每個 使用--[[RANDOMNUMBER and textbox1 Text]] ,但是如何為每次替換選擇一個新數字,所以它並不總是 241848 之類的?

Random random = new Random();
string replacing = " --[[" + random.Next() + textBox1.Text + "]] ";
string output = richTextBox1.Text.Replace(" ", replacing);

使用Regex.Replace(String, String, MatchEvaluator)代替。 它需要一個MatchEvaluator回調函數,您可以在其中提取下一個隨機數:

Random random = new Random();
string output = Regex.Replace(richTextBox1.Text, " ", (match) => 
    string.Format(" --[[{0}{1}]] ", random.Next(), textBox1.Text));

例如:

Random random = new Random();
string output = Regex.Replace("this is a test", " ", (match) => 
    string.Format(" --[[{0}{1}]] ", random.Next(), "sample"));

上面的示例輸出:

this --[[1283057197sample]] is --[[689040621sample]] a --[[1778328590sample]] test

這是使用 String.Split 和 Linq Aggregate 的解決方案。

string source = "This is a test string with multiple spaces";
string replaceText = "TextToReplace";
string template = " --[[{0}{1}]] ";
System.Random rand = new System.Random();

var splitString = source.Split(' ');
var result = splitString.Aggregate((a,b) => a + String.Format(template, rand.Next().ToString(), replaceText) + b);

而不是使用Replace ,您將不得不使用IndexOf並自己進行替換,每次使用一個新的隨機數。 偽代碼:

var index = str.IndexOf(' ');

while (index != -1)
{
    str = str.Substring(0, index) + rand.Next() + str.Substring(index + 1, str.Length - index - 1);
    index = str.IndexOf(' ');
}

我沒有測試這個,所以你可能想檢查 +1 或 -1 的位置實際上是有序的,而且這可以以更好的方式實現。 但這就是想法。

您的問題是 Random 僅被調用一次,因為 Replace 采用字符串參數。 一個快速而骯臟的解決方案是

        const string str = "string with lot of spaces";
        var newStr = new StringBuilder();
        foreach (var charc in str.ToCharArray())
        {
            if (charc.Equals(' '))
            {
                var random = new Random();
                var yourReplacementString = " --[[" + random.Next() + "textBox1.Text" + "]] ";
                newStr.Append(yourReplacementString);
            }
            else
            {
                newStr.Append(charc);
            }
        }

考慮 StringBuilder 以避免許多字符串初始化

var builder = new StringBuilder();

        var stingParts = richTextBox1.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < stingParts.Length; i++)
        {
            builder.Append(stingParts[i]);
            builder.Append(string.Format(" --[[{0}{1}]] ", random.Next(), textBox1.Text)));
        }

        var output = builder.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM