String replacement - C #
12 replies
Regular expressions, as selective, are the simplest and shortest.
I wonder if lower will 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();
Assuming this will depend on several things, including the length of the string.
+1
source to share
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();
}
0
source to share