有人问起这个问题:
有字符串如下:
ds32Christchurch 2 b 1200 - Rosamond J.S3.
ston 2 a 916 - Sidney 34
5 a 408 - Thomas A. 12 Youkq k
3hitehaven 10 b 1317
要求返回一行中相对数字比较集中最后的一个索引
以上结果应为
1200 后面的第一个位置
916 后面的一个位置
408 后面的一个位置
1317 后面的一个位置
匆忙写下算法,留待改进:
基
本算法:先把字符串转成一个字符数组,然后循环,取三个变量maxLength,tempMax,maxIndexPosition,,当连续为数字
时,tempLength++,然后与maxLength比较,记下maxLength和maxIndexPosition,直到行结束。
代码:
/// <summary>
/// 获取一行字符串中数字连续了大值的位置,如
/// static string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
/// 中的位置为1200后,即29
/// <a title="邀月工作室" href="http://blog.youkuaiyun.com/downmoon/" mce_href="http://blog.youkuaiyun.com/downmoon/" >欢迎与邀月交流,net技术与软件架构</a>(邀月) 2009.9.18 3w@live.cn
/// </summary>
/// <param name="sOrg">原始字符串</param>
/// <returns></returns>
public static int GetPosition(string sOrg)
{
int result = -1;
if (string.IsNullOrEmpty(sOrg)) { return result; }
int maxlength = 0;//最大连续长度
int maxIndex = -1;//怪大连续值的索引位置
int index = -1;//临时索引
int temp = 0;//临时变量,用于和最大连续值的比较
foreach (char c in sOrg)
{
index++;//索引位置累加
if (Char.IsDigit(c))
{
temp++;
if (temp > maxlength)
{
maxlength = temp;//记录连续数字最大值
maxIndex = index + 1;//记录连续数字最大值的索引位置
result = maxIndex;
}
}
else { temp = 0; }
}
return result;
}
测试代码:
public static void Main(string[] args)
{
string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
//string str = "ston 2 a 916 - Sidney 34 ";
Console.WriteLine("该行中数字比较集中的位置是:" + GetPosition(str));
Console.ReadKey();
}
得出结果:29
代码说明:
注意,此处使用Char.IsDigit(c) 没有用 Char.IsNumber(c)
关于这两个方法的区别,请查看MSDN
这个可以做个简单测试
public static void TestNumber()
{
for (int i = 0; i <= 0xffff; ++i)
{
char c = (char)i;
if (Char.IsDigit(c) != Char.IsNumber(c))
{
Console.WriteLine("Char value {0:x} IsDigit() = {1}, IsNumber() = {2}", i, Char.IsDigit(c), Char.IsNumber(c));
}
}
}