ds32Christchurch 2 b 1200 - Rosamond J.S3. ston 2 a 916 - Sidney 34 5 a 408 - Thomas A. 12 Youkq k3hitehaven 10 b 1317 要求返回一行中相对数字比较集中最后的一个索引以上结果应为1200 后面的第一个位置916 后面的一个位置408 后面的一个位置1317 后面的一个位置
2 回答
杨__羊羊
TA贡献1943条经验 获得超7个赞
基本算法:先把字符串转成一个字符数组,然后循环,取三个变量maxLength,tempMax,maxIndexPosition,,当连续为数字时,tempLength++,然后与maxLength比较,记下maxLength和maxIndexPosition,直到行结束。
//static string str = @"ds32Christchurch 2 b 1200 - Rosamond J.S3. ";
/// <summary>
/// 获取一行字符串中数字连续了大值的位置,如
/// 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;//最大连续长度
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. ";
Console.WriteLine("该行中数字比较集中的位置是:" + GetPosition(str));
Console.ReadKey();
}- 2 回答
- 0 关注
- 614 浏览
添加回答
举报
0/150
提交
取消
