Remove special characters and spaces from a string?

Asked

Viewed 5,645 times

6

I have a problem, in an app I’m picking up the contacts from the phone book, but I want to do a treatment on the numbers of the contacts 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 take only the last 8 characters of the number (to take operator etc), now how do I remove characters other than numbers of these string? In the example above all numbers would look like this: 99999999

  • Just for the record, there are nine-digit numbers too, in some regions. Soon, picking up the last 8 characters may not be the best option depending on the use of your app.

  • Here I got the 8 digits because the app is for Windows Phone (which has no tool that puts 9 digit) and I’m treating it later.

2 answers

7


Someone will give a solution with Regex, but I prefer so, using extension method:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

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

You can do it 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();
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • What do you mean optimized? Uses less memory feature? or what ?

  • Memory and processing.

5

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

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

Running on . Netfiddle: https://dotnetfiddle.net/0cid0m

Browser other questions tagged

You are not signed in. Login or sign up in order to post.