how to I replace all characters and numbers in string except several chars, for example "f", "a", "l" to avoid somthing like this:
String str = "replace different characters except several";
Console.WriteLine("Input: " + str);
str = str.Replace('a', '.').Replace('b', '.').Replace('c', '.');
Console.WriteLine("Output: " + str);
Use Regex for these kind of scenarios:
String str = "replace different characters except several";
str = Regex.Replace(str, @"[^fal]", "."); //Replace all with "." EXCEPT f,a,l
Console.WriteLine(str);
Output:- "...la.....ff........aa.................al"
One way would be using Linq
and replacing every character except those in excluded list.
char[] excluded = new char[] {'f', 'a', 'l'};
var output = new string(str.Select(x=> excluded.Contains(x)? x:'.').ToArray());
Check this demo
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.