Extracting a number from a string?

  • Thread starter Thread starter ORC
  • Start date Start date
O

ORC

Is there an easy way to extract a number from a string like:
result = ExtractNumber("this is a 4 string");

which should give the result = 4;

Thanks
Ole
 
Split the string and then parse all of the substrings. If the substring
parses without an exception, it's a number.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
like this..

foreach(string s in originalstring.Split(new char[]{' '}))
{
try
{
int n=int.Parse(s);
MessageBox.Show("Found the number "+n.ToString());
}
catch(Exception)
{
MessageBox.Show(s+" isn't a number!");
}
}

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Hi,

No, for this you should use regular expressions , extract the number(s) and
then use Convert.ToInt()

Cheers,
 
Back
Top