1

what is the faster way to trim all alphabet in a string that have alphabet prefix. For example, input sting "ABC12345" , and i wish to havee 12345 as output only. Thanks.

user6606188
  • 33
  • 1
  • 4
  • Possible repost ... check this link: http://stackoverflow.com/questions/13773610/using-regex-split-to-remove-anything-non-numeric-and-splitting-on – Kerry White Jul 19 '16 at 02:39
  • Try a [Regular Expression, like on this SO post](http://stackoverflow.com/a/19715367/3407841) – leetibbett Jul 19 '16 at 02:41

4 Answers4

9

Please use "char.IsDigit", try this:

static void Main(string[] args)
{
    var input = "ABC12345";
    var numeric = new String(input.Where(char.IsDigit).ToArray());
    Console.Read();
}
Fan TianYi
  • 397
  • 2
  • 11
2

You can use Regular Expressions to trim an alphabetic prefix

var input = "ABC123";
var trimmed = Regex.Replace(input, @"^[A-Za-z]+", "");

// trimmed = "123"

The regular expression (second parameter) ^[A-Za-z]+ of the replace method does most of the work, it defines what you want to be replaced using the following rules:

The ^ character ensures a match only exists at the start of a string
The [A-Za-z] will match any uppercase or lowercase letters
The + means the upper or lowercase letters will be matched as many times in a row as possible

As this is the Replace method, the third parameter then replaces any matches with an empty string.

Community
  • 1
  • 1
2

The other answers seem to answer what is the slowest way .. so if you really need the fastest way, then you can find the index of the first digit and get the substring:

string input = "ABC12345";
int i = 0;
while ( input[i] < '0' || input[i] > '9' ) i++;
string output = input.Substring(i);

The shortest way to get the value would probably be the VB Val method:

double value = Microsoft.VisualBasic.Conversion.Val("ABC12345"); // 12345.0
Slai
  • 22,144
  • 5
  • 45
  • 53
  • This is faster. But! It may be useful to have the additional functionality provided by `char.IsNumber()` – moarboilerplate Jul 19 '16 at 02:59
  • @moarboilerplate `char.IsNumber()` will be a bit slower because it has some additional unicode checks http://referencesource.microsoft.com/#mscorlib/system/char.cs,33394fddc2eca22a – Slai Jul 19 '16 at 03:05
0

You would have to regular expression. It seems you are looking for only digits and not letters.

Sample:

string result =
  System.Text.RegularExpressions.Regex.Replace("Your input string", @"\D+", string.Empty);
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17