Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of number from a string in C#

Tags:

c#

Form the below string I would like to get the index of the starting number.Please let me know how this can be done in C#.net.

For example

University of California, 1980-85.  
University of Colorado, 1999-02 
like image 723
Cool Coder Avatar asked Sep 17 '10 05:09

Cool Coder


People also ask

How do you find the index of a number in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Can you index a string in c?

The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.

What does indexOf do in c?

IndexOf(char x) method. This method returns the zero-based index of the first occurrence of the specified character within the string. In case no such character is found then it returns -1.


2 Answers

using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace IndexOfAny {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("University of California, 1980-85".IndexOfAny("0123456789".ToCharArray()));         }     } } 
like image 129
mpen Avatar answered Sep 20 '22 14:09

mpen


Following might help you to achieve your task

Regex re = new Regex(@"\d+");
Match m = re.Match(txtFindNumber.Text);
if (m.Success) 
{
    lblResults.Text = string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString());
}
else 
{
    lblResults.Text = "You didn't enter a string containing a number!";
}
like image 32
Pranay Rana Avatar answered Sep 17 '22 14:09

Pranay Rana