基本算法:先把字符串轉(zhuǎn)成一個(gè)字符數(shù)組,然后循環(huán),取三個(gè)變量maxLength,tempMax,maxIndexPosition,,當(dāng)連續(xù)為數(shù)字時(shí),tempLength++,然后與maxLength比較,記下maxLength和maxIndexPosition,直到行結(jié)束。
//static string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
/// <summary>
/// 獲取一行字符串中數(shù)字連續(xù)了大值的位置,如
/// static string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
/// 中的位置為1200后,即29
/// downmoon(邀月) 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;//最大連續(xù)長度
int maxIndex = -1;//怪大連續(xù)值的索引位置
int index = -1;//臨時(shí)索引
int temp = 0;//臨時(shí)變量,用于和最大連續(xù)值的比較
foreach (char c in sOrg)
{
index++;//索引位置累加
if (Char.IsDigit(c))
{
temp++;
if (temp > maxlength)
{
maxlength = temp;//記錄連續(xù)數(shù)字最大值
maxIndex = index + 1;//記錄連續(xù)數(shù)字最大值的索引位置
result = maxIndex;
}
}
else { temp = 0; }
}
return result;
}
測試:
public static void Main(string[] args)
{
string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
Console.WriteLine("該行中數(shù)字比較集中的位置是:" + GetPosition(str));
Console.ReadKey();
}