问题
I am trying to replace every
with --[[RANDOMNUMBER and textbox1 Text]]
, but how do I select a new number for each replace, so it's not always 241848 or such?
Random random = new Random();
string replacing = " --[[" + random.Next() + textBox1.Text + "]] ";
string output = richTextBox1.Text.Replace(" ", replacing);
回答1:
Use Regex.Replace(String, String, MatchEvaluator) instead. It takes a MatchEvaluator callback function where you can pull the next random number:
Random random = new Random();
string output = Regex.Replace(richTextBox1.Text, " ", (match) =>
string.Format(" --[[{0}{1}]] ", random.Next(), textBox1.Text));
For example:
Random random = new Random();
string output = Regex.Replace("this is a test", " ", (match) =>
string.Format(" --[[{0}{1}]] ", random.Next(), "sample"));
Sample output from above:
this --[[1283057197sample]] is --[[689040621sample]] a --[[1778328590sample]] test
回答2:
Here is a solution using String.Split and 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);
回答3:
Instead of using Replace
, you're going to have to use IndexOf
and make the replacement yourself, using a new random number every time. Pseudo code:
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(' ');
}
I didn't test this so you might wanna check where +1 or -1 is actually in order, and also this can be implemented in a better way. But that's the idea.
回答4:
Your problem is Random is being called only once since Replace takes string parameter. A quick and dirty solution would be
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);
}
}
回答5:
Consider StringBuilder to avoid many string initialization
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();
来源:https://stackoverflow.com/questions/25851885/how-can-i-replace-each-string-match-with-a-different-number