I'm pretty familiar with finding and replacing things in an array, but I'm having trouble finding out how to replace specific parts of a string. For instance, say the first item in my array is a string of sixteen random numbers like 1786549809654768. How would I go about replacing the first twelve characters with x's for example?
Asked
Active
Viewed 58 times
0
-
See Jon Skeet's answer here - http://stackoverflow.com/a/9367156/225600. – Prescott May 13 '15 at 22:08
2 Answers
2
Because string
can be translated to and from an array of char
you could easily transform your problem into replace things in an array problem:
char[] characters = input.ToCharArray();
// do your replace logic here
string result = new string(characters);
Or you could use Substring
. Assuming n
is number of characters you want to replace from the beginning or the string:
string result = new string('x', n) + input.Substring(n);

MarcinJuraszek
- 124,003
- 15
- 196
- 263
1
You can use Linq:
String test = "1234123412341234";
string output = new String(test.Select((c, index) => index < 12 ? 'x' : c).ToArray());
Console.WriteLine(output);
//xxxxxxxxxxxx1234

Rodrigo López
- 4,039
- 1
- 19
- 26