I have some strings like "pan1", "pan2", and "pan20" etc. I need to extract number. I use it:
char ch = s[(s.Length) - 1];
int n = Convert.ToInt32(Char.GetNumericValue(ch));
But in case of, for example, "pan20" the result is not correct 0.
I have some strings like "pan1", "pan2", and "pan20" etc. I need to extract number. I use it:
char ch = s[(s.Length) - 1];
int n = Convert.ToInt32(Char.GetNumericValue(ch));
But in case of, for example, "pan20" the result is not correct 0.
if you know where is the starting index of the number then simply you can do this :
string str = "pan20";
int number = Convert.ToInt32(str.Substring(3));
Note that "3" is the starting index of the number.
try to remove "pan" from the string; like this
string str = "pan20";
int number = Convert.ToInt32(str.Replace("pan", ""));
use regular expression only when string contains undetermined text inside
string str = "pan20";
int number = Convert.ToInt32(System.Text.RegularExpressions.Regex.Match(str, @"\d+").Value;
You can use for example regular expressions, for example [0-9]+$
to get the numbers in the end. See the Regex class in MSDN.