我想从下面的字符串中获取起始数字的索引,请告诉我如何在C#.net中实现。
例如:
University of California, 1980-85.
University of Colorado, 1999-02
我想从下面的字符串中获取起始数字的索引,请告诉我如何在C#.net中实现。
例如:
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()));
}
}
}
.ToCharArray()
这一部分,是吗? - mpenstring
转换为char[]
,这可能需要时间。虽然确实需要这样做,但只需执行一次即可。 - krillgarRegex 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!";
}
我不确定这是否是最快的方法(我认为它必须比Regex
更快),但你可以使用内置的字符串方法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
编辑:我在进行的一个简单测试中发现,我的方法似乎要快得多:
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;
}
运行结果1:
Regex totalTicks1 = 4851
IndexOfAny totalTicks2 = 1472
运行结果2:
Regex totalTicks1 = 5578
IndexOfAny totalTicks2 = 1470
运行结果3:
Regex totalTicks1 = 5441
IndexOfAny totalTicks2 = 1481
这看起来是一个很大的区别。我想知道不同长度的字符串会如何影响它...除非我真的在寻找某种复杂模式,否则我尽量避免使用Regex
,因为它总是感觉非常慢。
编辑2:修正了测试,使其更准确,char[]
和Regex
预定义在循环外部。