tags:

views:

121

answers:

5

How can I take only the number from strings in this format:

       "####-somestring"
       "###-someotherstring"
       "######-anotherstring"
+3  A: 
string s =  "####-somestring";
string digits = s.Substring(0, s.IndexOf("-") - 1);
int parsedDigits = int.Parse(digits);

for more complicated combinations you'd have to use Regex.

Femaref
+10  A: 
int.parse( Regex.match(String, @"\d+").value)
rerun
I think just \d+ would do it
Jesse
Of course, you'd need a closing ", but this gets my upvote. You'd need to account for no-match situations too.
BenAlabaster
very simple +1!
dboarman
\d would do it just habit. you don't need the () since i'm not using a capture or a group
rerun
+2  A: 

if you are sure they will always have a '-' in them you can use the string split function.

string cutThisUp = "######-anotherstring";
string[] parts = cutThisUp.Split(Convert.ToChar("-"));
int numberPart = Convert.ToInt32(parts[0]);
nbushnell
Just FYI, You don't need to call `Convert.ToChar("-")`; use single quotes to indicate a `char` rather than a `string` (so: `cutThisUp.Split('-')`).
Dan Tao
cool, thanks Dan.
nbushnell
+1  A: 

You could use something like the following:

string s = "####-somestring";
return Regex.Match(s, "(\d)+").Value);
+1  A: 

Yet another option: split on the - character and try to parse the first item in the resulting array (this is the same as nbushnell's suggestion, with a little added safety):

public bool TryGetNumberFromString(string s, out int number) {
    number = default(int);

    string[] split = s.Split('-');
    if (split.Length < 1)
        return false;

    return int.TryParse(split[0], out number);
}
Dan Tao