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
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
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()));
}
}
}
string to char[]. Your suggestion seemed very intuitive, and I'm not sure why that doesn't work, other than that a string has all the behavior and properties of a char[] without actually being one..ToCharArray() bit did you?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!";
}
Not sure if this is the fastest way (I assume it has to be faster than Regex) but you can just do it with a 1 liner using the built in string method IndexOfAny:
string yourString = "University of California, 1980-85";
int index = yourString.IndexOfAny(new char[]
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
// index = 26
// if nothing found it would be -1
EDIT: My method seems to be much faster in a simple test I did:
string test = "University of California, 1980-85";
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
long totalTicks1 = 0;
long totalTicks2 = 0;
char[] testChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Regex re = new Regex(@"\d+");
for (int i = 0; i < 1000; i++)
{
watch.Reset();
watch.Start();
Match m = re.Match(test);
watch.Stop();
totalTicks1 += watch.ElapsedTicks;
watch.Reset();
watch.Start();
int index = test.IndexOfAny(testChars);
watch.Stop();
totalTicks2 += watch.ElapsedTicks;
}
Run result 1:
Regex totalTicks1 = 4851
IndexOfAny totalTicks2 = 1472
Run result 2:
Regex totalTicks1 = 5578
IndexOfAny totalTicks2 = 1470
Run result 3:
Regex totalTicks1 = 5441
IndexOfAny totalTicks2 = 1481
This looks like a significant difference. I wonder how it would be affected by different lengths of strings as well... I try to stay away from Regex except in situations where I am truly looking for some type of complex pattern as it always seems real slow.
EDIT 2: Fixed up test to make it more accurate with the char[] and Regex predefined outside of the loop.