Home > Blockchain >  How to replace all non-valid characters in string?
How to replace all non-valid characters in string?

Time:03-07

How would I go about in replacing every character in a string which are not the following: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.@-

with -

So for example, the name Danny D'vito would become DannyD-vito

My inital though was converting string to char[] and looping through and checking each character, then convert back to string. But my hunch is telling me there must be an easier way to do this

CodePudding user response:

Regex.Replace() approach

string input = "Danny D'vito";
string result = new Regex("[^a-zA-Z0-9_.@-]").Replace(input, "-");

CodePudding user response:

You could use LINQ:

string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.@-";
string text = "Danny D'vito";
string result = string.Concat(text.Select(c => valid.Contains(c) ? c : '-'));

String.Concat is using a StringBuilder, so this is efficient.

  • Related