views:

267

answers:

4

I figure regex is overkill also it takes me some time to write some code (i guess i should learn now that i know some regex).

Whats the simplest way to separate the string in an alphanumeric string? It will always be LLLLDDDDD. I only want the letters(l's), typically its only 1 or 2 letters.

+5  A: 

TrimEnd:

string result = input.TrimEnd(new char[]{'0','1','2','3','4','5','6','7','8','9'});
// I'm sure using LINQ and Range can simplify that.
// also note that a string like "abc123def456" would result in "abc123def"

But a RegEx is also simple:

string result = Regex.Match(input,@"^[^\d]+").Value;
Michael Stum
wow i had no idea you can have a one liner regex.
acidzombie24
Not all Regexes have to be complicated. In fact, some of the more complex ones can sometimes be better replaced with a traditional code construct. Knowing only a few concepts (Character Classes, Backtracking, Named Groups) is good enough to efficiently solve a lot of the everyday string handling issues - definitely worth learning the basics!
Michael Stum
+3  A: 

I prefer Michael Stum's regex answer, but here's a LINQ approach as well:

string input = "ABCD1234";
string result = new string(input.TakeWhile(c => Char.IsLetter(c)).ToArray());
Ahmad Mageed
+1  A: 

You can use a regular expression that matches the digits to remove them:

input = Regex.Replace(input, "\d+$", String.Empty);

The old fashioned loop isn't bad either, it should actually be the fastest solution:

int len = input.Length;
while (input[len-1] >= '0' && input[len-1] <= '9') len--;
input = input.Substring(0, len);
Guffa
That ^ should be a $ - otherwise you are matching numbers before the start of the string ;)
Richard Szalay
@Richard: Yes, you are absolutely right. :)
Guffa
A: 

They've got it - note the good solutions use the not operator to employ your problem description: "Not numbers" if you had the numbers at the front seems from my limited gains that you have to have what is called capturing groups to get past whatever it is on the front-end of the string. The design paradigm I use now is not delimiter character, followed by delimiter character, followed by an opening brace.

That results in needing a delimiter character that is not in the result set, which for one thing can be well established ascii values for data-delimitersl eg 0x0019 / 0x0018 and so on.

Nicholas Jordan