问题
How can I determine what number (with an arbitrary number of digits) is at the start of a string?
Some possible strings:
1123|http://example.com
2|daas
Which should return 1123 and 2.
回答1:
You can use LINQ:
string s = "35|...";
int result = int.Parse(new string(s.TakeWhile(char.IsDigit).ToArray()));
or (if the number is always followed by a |
) good ol' string manipulation:
string s = "35|...";
int result = int.Parse(s.Substring(0, s.IndexOf('|')));
回答2:
Use a regular expression:
using System.Text.RegularExpressions;
str = "35|http:\/\/v10.lscache3.c.youtube.com\/videoplayback...";
Regex r = new Regex(@"^[0-9]{1,2}");
Match m = r.Match(str);
if(m.Success) {
Console.WriteLine("Matched: " + m.Value);
} else {
Console.WriteLine("No match");
}
will capture 1-2 digits at the beginning of the string.
回答3:
if you know that the number is always going to be 2 digits:
string str = "35|http:\/\/v10.lscache3.c.youtube.com\/videoplayback?...";
int result;
if (!int.TryParse(str.Substring(0, 2), out result)) {
int.TryParse(str.Substring(0, 1), out result)
}
// use the number
if you're not sure how long the number is, look at the .indexOf() approach by dtb. If you need something much more complex, only then consider using regex.
回答4:
You can get the two first characters and convert to int.
var s = "a35|...";
short result = 0;
bool isNum = Int16.TryParse(s.Substring(0, 2), out result);
来源:https://stackoverflow.com/questions/3809021/how-do-i-determine-if-there-are-two-or-one-numbers-at-the-start-of-my-string