The most efficient way to separate a string

I have this line:

"B82V16814133260"

which would be the most efficient way to extract two strings:

left side String: "B82V" rigth part string: "16814133260"

The rule is this: take all the numbers on the right side and create a line from them, then take a reminder and put it on another line.

This is my decision, but it is too cumbersome! How to make it short and effective?

String leftString = ""; String rightString=""; foreach (char A in textBox13.Text.Reverse()) { if (Char.IsNumber(A)) { rightString += A; } else { break; } } char[] arr = rightString.ToArray(); Array.Reverse(arr); rightString=new string(arr); leftString = textBox13.Text.Replace(rightString, ""); 
+7
source share
6 answers

This gives what you expect:

 var given = "B82V16814133260"; var first = given.TrimEnd("0123456789".ToCharArray()); var rest = given.Substring(first.Length); Console.Write("{0} -> {1} -- {2}", given, first, rest); // B82V16814133260 -> B82V -- 16814133260 
+14
source

Well, the other answer is probably better, but I wrote this anyway, so I post it:

Needs:

 using System.Text.RegularExpressions; 

The code:

 string str = "B82V16814133260"; string[] match = Regex.match(str, @"^([\d\w]+?\w)(\d+)$").Groups; string left = match[1]; string right = match[2]; 
+5
source

This should be very fast:

 int index = text.Length - 1; while (index >= 0 && Char.IsDigit(text[index])) { index--; } string left = text.Substring(0, index + 1); string right = text.Substring(index + 1); 
+4
source

I read "most effective" as "fastest."

I wrote a quick test with a long string running 10 million times.

Austin's TrimEnd ran in 4.649s

My solution started in 1.927 seconds

  int j = given.Length - 1; for (; j >= 0; j--) { char c = given[j]; if (c < '0' || c > '9') { break; } } var first = given.Substring(0, j + 1); var rest = given.Substring(j + 1); 

Please note that my assemblies were not debugging (when debugging, my solution is slower, but this is because TrimEnd does not work in debug bits). So, if you use my code in your application and build debugging, it will be slower.

+2
source

I like linq.

  var s = "B82V16814133260"; var lastNonNumeric = s.Reverse().Where(x => !char.IsDigit(x)).FirstOrDefault(); var index = s.LastIndexOf(lastNonNumeric); var secondString = s.Substring(index + 1); var firstString = s.Substring(0, index+1); 

This may not be the best or most reliable solution, but it works for your test string.

+1
source
  string Source = textBox13.Text; for (i = Source.Length - 1; i >=0; i--) { if (! Char.IsNumber(Source[i]) break; } string leftString = Source.Left(i+1); string rightString = Source.Right(i+1,Source.Length-i-1); 
0
source

All Articles