读书人

统计字符串解决方法

发布时间: 2013-03-10 09:38:39 作者: rapoo

统计字符串
如有以下字符串
a1 b2 c3 d5 a4 a5
a3 a5 b12 d18 c8 a12
b13 c11 d12 a11 d2 d8

求前面是a,后面数字在1-5的个数,6-10的个数,10以上的个数
前面是b,后面数字是1-5的个数,6-10的个数,10以上的个数
以下类推。。。

这个要怎么写
[解决办法]
这个简单,把下面的代码粘贴进去就可以了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = @"a1 b2 c3 d5 a4 a5
a3 a5 b12 d18 c8 a12
b13 c11 d12 a11 d2 d8";
var query = Regex.Matches(s, @"([a-z])(\d+)")
.Cast<Match>()
.Select(x => new { a = x.Groups[1].Value, b = int.Parse(x.Groups[2].Value) })
.GroupBy(x => new { x.a, b = x.b <= 5 ? "1~5" : (x.b <= 10 ? "6~10" : ">10") })
.OrderBy(x => x.Key.a)
.Select(x => string.Format("{0} {1}有{2}个。", x.Key.a, x.Key.b, x.Count()));
foreach (var item in query)
Console.WriteLine(item);
}
}
}


a 1~5有5个。
a >10有2个。
b 1~5有1个。
b >10有2个。
c 1~5有1个。
c 6~10有1个。
c >10有1个。
d 1~5有2个。
d >10有2个。
d 6~10有1个。
Press any key to continue . . .
[解决办法]
  string str = @"a1 b2 c3  d5  a4 a5
a3 a5 b12 d18 c8 a12
b13 c11 d12 a11 d2 d8";
var list = Regex.Matches(str, @"([a-z])((?<a>[1-5])
[解决办法]
(?<b>10
[解决办法]
[6-9])
[解决办法]
(?<c>[1-9]\d+))(?:\s+
[解决办法]
$)").OfType<Match>().Select(t => new
{


key = t.Groups[1].Value,
a = t.Groups["a"].Value == "" ? 0 : 1,
b = t.Groups["b"].Value == "" ? 0 : 1,
c = t.Groups["c"].Value == "" ? 0 : 1,
}).OrderBy(t => t.key).GroupBy(t => t.key).Select(t =>
string.Format("{0} 1-5有{1}个 6-10有{2}个 大于10有{3}个", t.Key, t.Sum(tt => tt.a), t.Sum(tt => tt.b), t.Sum(tt => tt.c)));
list.ToList().ForEach(t=>Console.WriteLine(t));

读书人网 >C#

热点推荐