Silver
Silver

Reputation: 23

How to replace each digit in a string with a different character?

I am trying to get a string, for example, "e1e2e3" to have each digit replaced with a different character, which in this case would be a random number. Whereas instead of e1e2e3, it could be something like e5e9e1 because each number is replaced with a random one.

I tried

string txt = textBox1.Text;
Regex digits = new Regex(@"\d", RegexOptions.None);
Random rand = new Random();
txt = digits.Replace(txt, rand.Next(0, 9).ToString());
MessageBox.Show(txt);

The problem is, every single number is replaced with the same random number. "e1e2e3" would then be something like "e2e2e2" where each number is the same.

Upvotes: 2

Views: 263

Answers (2)

fubo
fubo

Reputation: 45947

approach without RegEx

string txt = "e1e2e3";           
Random rand = new Random();
string res = string.Concat(txt.Select(x => char.IsDigit(x)?(char)('0'+rand.Next(0, 9)):x));

Side note to the second int parameter of Next(int,int)

The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

if you want values between 0 and 9, you should use Next(0, 10)

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163207

You are almost there, you can use the callback of Regex.Replace to create a random value for each replacement, instead of using a single random value.

If you just want to match digits 0-9 you can use [0-9] instead of \d as the latter could match all Unicode digits

string txt = textBox1.Text;
Regex digits = new Regex(@"\d", RegexOptions.None);
Random rand = new Random();
txt = digits.Replace(txt, match => rand.Next(0, 9).ToString());
MessageBox.Show(txt);

See a C# demo

Upvotes: 3

Related Questions