日期:2014-05-19  浏览次数:20851 次

从字符串中读取指定的子字符串
在TXT文本中,
[T1]123
[T2]123
[T3]123
[T1]123
[T2]123
[T3]123
...


现已从TXT文本中将数据读读入一个string数据类型中,
求教如何实现:
1。统计属性[T1],[T2],[T3]各个出现的次数
2。累记属性[T1的数值



------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] counts = new int[] { 0, 0, 0 };
int sumT3 = 0;
Regex regex = new Regex(@ "\[T(\d)\](\d+) ");
foreach (string line in System.IO.File.ReadAllLines( "TextFile1.txt "))
{
Match match = regex.Match(line);
int index = Int32.Parse(match.Groups[1].Value);
int value = Int32.Parse(match.Groups[2].Value);
counts[index - 1]++;
if (index == 3)
{
sumT3 += value;
}
}
Console.WriteLine( "T1 {0} T2 {1} T3 {2} ",counts[0],counts[1],counts[2]);
Console.WriteLine( "Sum of T3 {0} ",sumT3);
}
}
}
我是不是太无聊了