Edit strings of variable length
How can I take only the number from strings in this format:
"####-somestring"
"###-s开发者_运维技巧omeotherstring"
"######-anotherstring"
int.parse( Regex.match(String, @"\d+").value)
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]);
You could use something like the following:
string s = "####-somestring";
return Regex.Match(s, "(\d)+").Value);
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);
}
精彩评论