How to determine if there are two or one number at the beginning of my line?

How to determine which number (with an arbitrary number of digits) is at the beginning of a line?

Some possible lines:

1123|http://example.com
2|daas

Which should return 1123 and 2.

+3
source share
4 answers

You can use LINQ:

string s = "35|...";

int result = int.Parse(new string(s.TakeWhile(char.IsDigit).ToArray()));

or (if the number always follows |) good string manipulation:

string s = "35|...";

int result = int.Parse(s.Substring(0, s.IndexOf('|')));
+5
source

Use regex:

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 write 1-2 digits at the beginning of the line.

+6
source

, 2 :

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

, , .indexOf() dtb. - , .

0

int.

var s = "a35|...";
short result = 0;
bool isNum = Int16.TryParse(s.Substring(0, 2), out result);
0
source

Source: https://habr.com/ru/post/1766885/


All Articles