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.

user3560681
  • 101
  • 2
  • 7
  • 3
    Will all of your strings always have 'pan' in them? If so, just remove 'pan'. – Blue0500 May 17 '14 at 20:56
  • Yes, if 'pan' is consistent, use Substring to get the remaining text (after these three characters) and convert this to a number. – Andy G May 17 '14 at 20:56
  • http://stackoverflow.com/questions/4734116/find-and-extract-numbers-from-a-string – Soner Gönül May 17 '14 at 20:58
  • This question is not the same as the linked question "Find and extract numbers from a string". Here it's about the end of a string. The linked answer will find all integers in a string, forcing you to iterate through the Regex' results. @SamiKuhmonen gave the correct answer. – Maxwin Aug 19 '14 at 14:02

2 Answers2

3

Index Approach

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.


Fixed Prefix Approach

try to remove "pan" from the string; like this

string str = "pan20";
int number = Convert.ToInt32(str.Replace("pan", ""));

Regular Expression Approach

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;
Zaid Al-Omari
  • 711
  • 1
  • 8
  • 17
1

You can use for example regular expressions, for example [0-9]+$ to get the numbers in the end. See the Regex class in MSDN.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74