user6715803
user6715803

Reputation:

How to I replace all chars and numbers in string except several chars

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

Upvotes: 2

Views: 681

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16956

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

Upvotes: 0

GorvGoyl
GorvGoyl

Reputation: 49150

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........a.a..................al"

Upvotes: 2

Related Questions