How can I take only the number from strings in this format:
"####-somestring"
"###-someotherstring"
"######-anotherstring"
How can I take only the number from strings in this format:
"####-somestring"
"###-someotherstring"
"######-anotherstring"
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.
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]);
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);
}