2

I have some problems with replacing characters using .replace

Example:

string word = "Hello";
oldValue = "H";
newValue = "A"; 

word = word.replace(oldValue,newValue)

well the code above is working good, the H will be replaced with A and output will be Aello

now i want to use more newValue not just one so the H can be replaced with a random newValue not just only "A"

when i change newValue in:

newValue = 'A', 'B', 'C';

the .Replace function is giving me a error

JBntis
  • 79
  • 16
Bert Ernie
  • 33
  • 4

5 Answers5

2

Try using the System.Random class to get a random item within the newValue array.

string word = "Hello";
var rand = new System.Random();
var oldValue = "H";
var newValue = new[] { "A", "B", "C" };

word = word.Replace(oldValue, newValue[rand.Next(0, 2)]);
Kane
  • 16,471
  • 11
  • 61
  • 86
2

The Replace method doesn't support random replacements, you have to implement the random part yourself.

The Replace method doesn't support a callback for the replacement either, but the Regex.Replace method does:

string word = "Hello Hello Hello";
Random rnd = new Random();
string[] newValue = { "A", "B", "C" };
word = Regex.Replace(word, "H", m => newValue[rnd.Next(newValue.Length)]);

Console.WriteLine(word);

Example output:

Cello Bello Aello
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • out of curiosity which is faster using `string.Replace` or using a regular expression? – Kane Mar 06 '13 at 09:39
  • @Kane: The `String.Replace` method is naturally faster, but it doesn't support a callback for the replacement. – Guffa Mar 06 '13 at 09:41
  • Cool, thanks - it may seem odd but I really did not know which was faster, and was too lazy to do any sort of benchmarking. – Kane Mar 06 '13 at 09:42
0

Interesting task, but here is it :)

string word = "Hello";
char[] repl = {'A', 'B', 'C'};
Random rnd = new Random();
int ind = rnd.Next(0, repl.Length);

word = word.Replace('H', repl[ind]);

EDIT: the maxValue for rnd.Next is exclusive, so you should use the repl.Length instead of (repl.Length -1)

VladL
  • 12,769
  • 10
  • 63
  • 83
0

You can use a random string creation method and push it through the replace: Random String Generator Returning Same String

Community
  • 1
  • 1
JBntis
  • 79
  • 16
0

To replace with a random upper case letter (65-90) between A-Z.

string oldValue = "H";

string newValue = Convert.ToString((char)(new Random().Next(65, 91)));
word.Replace(oldValue, newValue);
Kaf
  • 33,101
  • 7
  • 58
  • 78