Remove special characters and spaces from a string?

5

I have a problem, in an app I'm picking up contacts from the phonebook, however I want to make a treatment in the contact numbers that can come like this:

(99) 9999-9999
9999-9999
9999 9999

and among other things, the only treatment I did was to use a SubString to cut and pick only the last 8 characters of the number (to take operator etc), now how do I remove characters other than those string ? In the above example all numbers would look like this: 99999999

    
asked by anonymous 15.11.2015 / 16:53

2 answers

5

Someone will give a solution with RegEx, but I prefer this:

var texto = "(99) 9999-9999";
foreach (var chr in new string[] {"(", ")", "-", " " }) {
    texo = texto.Replace(chr, "");
}

See working using extension method .

Obviously if you want to store this in the variable you need to store the method result again in the variable.

Can do more optimally. Example:

public static class StringExt {
    public static string Replace(this string str, string newValue, params char[] chars) {
        var sb = new StringBuilder();
        foreach (var chr in str) {
            if (!chars.Contains(chr)) {
                sb.Append(chr);
            } else {
                sb.Append(newValue);
            }
        }
        return sb.ToString();
    }
}

See running on dotNetFiddle .

    
15.11.2015 / 17:28
4

As predicted by @bigown, I'll show you the method using Regex .Replace () replacing everything in one line, feel free to choose how you want to work:

string strTexto = "(12) 3456-7890";
strTexto = Regex.Replace(strTexto, "[\(\)\-\ ]", "");
Console.WriteLine(strTexto);

Running on .NETFiddle: link

    
16.11.2015 / 17:27