How do I determine if there are two or one numbers at the start of my string?

元气小坏坏 提交于 2019-12-23 20:24:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!