Reputation: 7778
I have this string:
"B82V16814133260"
what would be the most efficient way to get two strings out of it:
left part String: "B82V" rigth part string: "16814133260"
The rule is this: take all numbers on the right side and create string out of them, then take the reminder and place it into another string.
This is my solution, but it is too bulky! How to do it short and efficient?
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, "");
Upvotes: 7
Views: 375
Reputation: 17362
Well, the other answer is probably better, but I wrote this anyway, so I'm posting it:
Needs:
using System.Text.RegularExpressions;
Code:
string str = "B82V16814133260";
string[] match = Regex.match(str, @"^([\d\w]+?\w)(\d+)$").Groups;
string left = match[1];
string right = match[2];
Upvotes: 5
Reputation: 4561
I read 'most efficient' as 'fastest'.
I wrote a quick test with a long string, running 10 million times.
Austin's solution to use TrimEnd
ran in 4.649s
My solution ran 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);
Note that my builds were not debug (in debug, my solution is slower, but that is because TrimEnd is not running in debug bits). So, if you are running my code in your application, and are building debug, it'll be slower.
Upvotes: 2
Reputation: 12821
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);
Upvotes: 0
Reputation: 50225
This yields what you're expecting:
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
Upvotes: 14
Reputation: 23088
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);
Probably not the best or most robust solution, but it works for your test string.
Upvotes: 1
Reputation: 6719
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);
Upvotes: 3