如题:
给定一个字符串,比如yycc12long34567yc,通过写一个小程序,将字符串中最长的数字取出来。
一开始我想到的是,遍历这个字符串每个字符,再根据是否数字拼接新的字符串,并存储到新的对象中
代码如下:
/// <summary>
/// 方法一
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn1_Click(object sender, EventArgs e)
{
string str = tbStr.Text;
int l = str.Length;
char[] chars = str.ToCharArray();
List<string> strTemp = new List<string>();
string sTemp = string.Empty;
int n = 0;
//遍历每个字符
foreach (char c in chars)
{
//是数字则累加
if (int.TryParse(c.ToString(), out n))
{
sTemp += c.ToString();
}
else
{
//否则将上次结果加到list,并置空
if (int.TryParse(sTemp, out n))
{
strTemp.Add(sTemp);
sTemp = string.Empty;
}
}
}
//最后一次结果是数字的加到list
if (int.TryParse(sTemp, out n))
{
strTemp.Add(sTemp);
sTemp = string.Empty;
}
string res = string.Empty;
//循环比较长度
for (int i = 0; i < strTemp.Count; i++)
{
for (int j = i + 1; j < strTemp.Count; j++)
{
if (strTemp[i].Length > strTemp[j].Length)
res = strTemp[i];
else
res = strTemp[j];
}
}
Response.Write(res);
}
后来,一哥们给了我个好建议,使用正则直接搞定,然后进行排序即可搞定
/// <summary>
/// 方法二(正则、list排序)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn2_Click(object sender, EventArgs e)
{
string str = tbStr.Text;
Regex rgx = new Regex("[\\d+]+");
MatchCollection mc = rgx.Matches(str);
List<Match> ms = new List<Match>();
foreach (Match m in mc)
{
ms.Add(m);
}
ms.Sort(delegate(Match a, Match b)
{
return a.Length.CompareTo(b.Length);
});
Response.Write(ms[ms.Count - 1].Value);
}
还学习了下List的排序
收获不小