Home > OS >  C# How can i split a string on first number?
C# How can i split a string on first number?

Time:04-21

I have the following string "ABCD EFG 201 E" i want to split it on the first number that it founds a digit and return both strings Ex. "ABCD EFG" and "201 E"

i tried Regex.Split and other stuff but i don't get it. can someone help me please? Thanks, Best Regards.

CodePudding user response:

not using regex cos I dont really like them - story goes "you have a problem, you decide to use regex on it, you now have 2 problems"

 char[] digits = {'0','1','2','3','4','5','6','7','8','9'};
 string s = "ABCD EFG 201 E";
 var idx = s.IndexOfAny(digits);
 if (idx !=-1){
     var first = s.Substring(0,idx);
     var second = s.Substring(idx);
 }

CodePudding user response:

Using Regex, you can do it like below :

    string Text = "ABCD EFG 201 E";  
    string[] digits = Regex.Split(Text, @"(\d.*)");  
    foreach (string value in digits)  
        Console.WriteLine(value); 

Code Here

  • Related