简体   繁体   中英

Replacing specific parts of a string in an array

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?

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);

You can use Linq:

String test = "1234123412341234";
string output = new String(test.Select((c, index) => index < 12 ? 'x' : c).ToArray());
Console.WriteLine(output);
//xxxxxxxxxxxx1234

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM