Say I have a string containing numbers and other chars.
I want to reduce the string to numbers only.
F.e. from 23232-2222-d23231 to 23232222223231
Can this be done with string.replace()?
if not, what's the simplest and shortest way?
10x!
There are a bunch of possibilities, from Regular Expressions to handling the text yourself. I'd go for this:
Regex.Replace(input, @"\D+", "")
Well, you will get about 874355876234857 answers with String.Replace and Regex.Replace, so here's a LINQ solution:
code = new String((from c in code where Char.IsDigit(c) select c).ToArray());
Or using extension methods:
code = new String(code.Where(c => Char.IsDigit(c)).ToArray());
Regex object, use the static Replace method, or did it recreate a couple dozen Regex objects? The first option would be fastest, though may not be representative of real world use.The best way would be to user Regular Expressions. You example would be:
RegEx.Replace("23232-2222-d23231", "\\D+", "");
+ or no quantifier. Using * will cause lots of 0-length matches.Regular expressions, as sampled, are the simplest and shortest.
I wonder if below would be faster?
string sample = "23232-2222-d23231";
StringBuilder resultBuilder = new StringBuilder(sample.Length);
char c;
for (int i = 0; i < sample.Length; i++)
{
c = sample[i];
if (c >= '0' && c <= '9')
{
resultBuilder.Append(c);
}
}
Console.WriteLine(resultBuilder.ToString());
Console.ReadLine();
guessing it would depend on a few things, including string length.
The simplest would be to use Replace.
string test = "23232-2222-d23231";
string newString = test.Replace("-","").Replace("d","");
But using REGEX would be better, but tougher.
You can use a regular expression.
string str = "sdfsdf99393sdfsd";
str = Regex.Replace(str, @"[a-zA-Z _\-]", "");
I've used this to return only numbers in a string before.
string str = "foo/234335"? Oops.