开发者

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜