Hi,
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!
Hi,
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!
Yes you can use String.replace but it would be wiser to use regex so that you can match alot more criteria with alot less effort
There a a bunch of possibilities, from Regular Expressions to handling the text yourself. I'd go for this:
Regex.Replace(input, @"\D+", "")
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.
The best way would be to user Regular Expressions. You example would be:
RegEx.Replace("23232-2222-d23231", "\\D+", "");
It is not (easily) possible with string.Replace()
. The simplest solution is the following function/code:
public string GetDigits(string input)
{
Regex r = new Regex("[^0-9]+");
return r.Replace(input, "");
}
I would use a regular expression.
See this post http://stackoverflow.com/questions/273141/regex-for-numbers-only
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.
You can use a simple extension method:
public static string OnlyDigits(this string s)
{
if (s == null)
throw new ArgumentNullException("null string");
StringBuilder sb = new StringBuilder(s.Length);
foreach (var c in s)
{
if (char.IsDigit(c))
sb.Append(c);
}
return sb.ToString();
}
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.
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());
Try
string str="23232-2222-d23231";
str=Regex.Replace(str, @"\D+", String.Empty);
You could use linq:
string allDigits = new String(input.Where(c => Char.IsDigit(c)).ToArray());