从下面文本文件中读取数据,数据格式如下:
6
刘德华#100#93#80
羽泉#80#88
王菲#90#90
SHE#90#100#70
赵本山#85#90
黑豹#50#85#80其中第1行表示有多少条数据,姓名中不会包含#字符,数值为整数。具体文本文件见data.txt将数值每行数值相加求和,并按照合计值排序(从高到低),并输出到文本文件中out.txtout.txt文件格式如下:6
刘德华#273
SHE#260
黑豹#215
王菲#180
赵本山#175
羽泉#168其中第1行表示有多少条数据
{
static void Main( string[] args )
{
StreamReader reader = File.OpenText( AppDomain.CurrentDomain.BaseDirectory + "data.txt" );
string path = AppDomain.CurrentDomain.BaseDirectory + "out.txt";
StreamWriter writer = null;
try
{
if( !File.Exists( path ) )
{
writer = File.CreateText( path );
}
else
{
writer = File.AppendText( path );
}
while( !reader.EndOfStream )
{
string str = reader.ReadLine();
string[] strs = str.Split( "#".ToCharArray() );
string result = strs[ 0 ];
if( strs.Length > 1 )
{
result += "#";
int iResult = 0;
for( int i = 1; i < strs.Length; ++i )
{
iResult += int.Parse( strs[ i ] );
}
result += iResult.ToString();
}
writer.WriteLine( result );
}
}
catch( Exception ex )
{
}
finally
{
if( reader != null )
{
reader.Dispose();
}
if( writer != null )
{
writer.Flush();
writer.Dispose();
}
}
}
}
foreach (Match match in Regex.Matches(str, @"[^#\d]+(?<num>[#\d]+)"))
{
int sum = 0;
string count = Regex.Replace(match.Groups["num"].Value, @"#(\d+)",
new MatchEvaluator(delegate(Match m)
{
sum += int.Parse(m.Groups[1].Value);
return m.NextMatch().Success ? "" : "#" + sum.ToString();
}));
str = str.Replace(match.Groups["num"].Value, count);
}
StreamWriter sw = File.CreateText("D:\\output.txt");
sw.Write(str);
sw.Close();