在C#中查找字符串中的数字索引

Coo*_*der 42 c#

从下面的字符串中我想得到起始编号的索引.请告诉我如何在C#.net中完成.

例如

University of California, 1980-85.  
University of Colorado, 1999-02 
Run Code Online (Sandbox Code Playgroud)

mpe*_*pen 73

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()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*ana 9

以下可能会帮助您完成任务

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!";
}
Run Code Online (Sandbox Code Playgroud)


Kel*_*sey 7

不确定这是否是最快的方式(我认为它必须比它更快Regex)但你可以使用内置的字符串方法使用1个线程来做到这一点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
Run Code Online (Sandbox Code Playgroud)

编辑:在我做的简单测试中,我的方法似乎要快得多:

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 Code Online (Sandbox Code Playgroud)

运行结果1:

Regex totalTicks1 = 4851
IndexOfAny totalTicks2 = 1472
Run Code Online (Sandbox Code Playgroud)

运行结果2:

Regex totalTicks1 = 5578
IndexOfAny totalTicks2 = 1470
Run Code Online (Sandbox Code Playgroud)

运行结果3:

Regex totalTicks1 = 5441
IndexOfAny totalTicks2 = 1481
Run Code Online (Sandbox Code Playgroud)

这看起来像是一个显着的差异.我想知道它会受到不同长度的琴弦的影响......我试图远离,Regex除非在我真正寻找某种类型的复杂模式的情况下,因为它总是看起来很慢.

编辑2:修正了测试,使其在循环外部char[]Regex预定义更准确.