views:

148

answers:

6

I have a string in this format: "ABC_123_"

I want to end up with and integer variable that is just the number portion of the string. What is the most efficient way to accomplish that in C#?

+8  A: 

This should be efficient enough. Don't sweat if it's not the most efficient unless profiling tells you that it's a bottleneck of your application:

string s = "ABC_123_";
int i = Int32.Parse(s.Split('_')[1]);

Without more information about your problem, this is what I would go with.

Jason
A: 

If your string input will always be in the same form of ABC_123_ then this will work

int i = Int32.Parse("ABC_123_".Substring(4, 3));
clichekiller
I hope you never give this answer at an interview.
Babak Naffas
@bnaffas: Could you provide some additional feedback?
clichekiller
A: 

If the lenght of your string etc. are fixed, you can use String.Substring.

The more complicated your string gets, the more you should use Regex.

winSharp93
+1  A: 

Here's one way. I don't know about "most efficient", but it should work:

int? GetJustIntPart(string original)
{
    var split = original.Split('_');
    int test;
    foreach (var item in split)
    {
        if (int.TryParse(item, out test))
            return test;
    }
    return null;
}
Kyralessa
This will work no matter where the numeric part is, instead of counting on it being in a certain position. It'll only return the *first* numeric part, though, if you have more than one.
Kyralessa
+3  A: 

Mandatory RegEx example to match all numbers in a string:

int num = Convert.ToInt32(Regex.Match("ABC_123_", @"\d+").Value);

Change to make sure it's surrounded by _:

int num = Convert.ToInt32(Regex.Match("ABC_123_", @"(?<=_)\d+(?=_)").Value);

Note: Value may be null/empty if your input string is in an improper format, so use int.TryParse or try/catch etc.

Michael Stum
much better of just using `Regex.Match("ABC_123_", @"_(\d+)_").Groups[1]` instead of lookaround in this situation imo.
Paul Creasey
True, although I don't know how much different performance there is, especially when using compiled Regex.
Michael Stum
+2  A: 

I'd go with int i = int.Parse(Regex.Match(string,@"\d+"));

Paul Creasey