麻烦一下大家,字符串排序问题
有一组字符串如下:
1=411002XXX,0505,北京丰台区,1,1,33,1,1
2=411252XXX,0312,北京丰台区,1,1,13,1,1
3=41123562XXX,0730,北京丰台区,1,1,66,1,1
4=4345002XXX,0920,北京丰台区,1,1,50,1,1
5=434202XXX,0104,北京丰台区,1,1,3,1,1
排序规则:用每行字符串第五个逗号后面的数字比大小,小的则把这行前两位数据(等号后面)和第五个逗号后面的数字,输出出来。
结果:
--------------------编程问答-------------------- 可能我描述的不太详细。我重新说一下
41123562XXX-0730-66
4345002XXX-0920-50
411002XXX-0505-33
411252XXX-0312-13
434202XXX-0104-3
现在有这样几个字符串:
asdgf-xcvx-6
sdfgv-nvbn-8
hkmnb-lkjr-10
tryhv-ouid-2
排序后的结果:
hkmnb-lkjr-10
sdfgv-nvbn-8
asdgf-xcvx-6
tryhv-ouid-2
想了几个钟头,试过几个办法都行不通啊,平时代码敲的太少了。 --------------------编程问答-------------------- 将字符串拆分,再排序,再组合。 --------------------编程问答-------------------- 随便写了下
--------------------编程问答--------------------
string[] inputs = {
"1=411002XXX,0505,北京丰台区,1,1,33,1,1",
"2=411252XXX,0312,北京丰台区,1,1,13,1,1",
"3=41123562XXX,0730,北京丰台区,1,1,66,1,1",
"4=4345002XXX,0920,北京丰台区,1,1,50,1,1",
"5=434202XXX,0104,北京丰台区,1,1,3,1,1"
};
var splittedQuery = from i in inputs
select i.Split(new char[]{ '=', ',' });
var sortQuery = from s in splittedQuery
orderby int.Parse(s[6]) descending
select s;
foreach (string[] line in sortQuery)
{
Console.WriteLine(line[1] + "-" + line[2] + "-" + line[6]);
}
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = @"1=411002XXX,0505,北京丰台区,1,1,33,1,1
2=411252XXX,0312,北京丰台区,1,1,13,1,1
3=41123562XXX,0730,北京丰台区,1,1,66,1,1
4=4345002XXX,0920,北京丰台区,1,1,50,1,1
5=434202XXX,0104,北京丰台区,1,1,3,1,1";
var query = Regex.Matches(s, @"\d\=([\dX]+),(\d+),\w+,\d,\d,(\d+),\d,\d")
.Cast<Match>()
.OrderByDescending(x => int.Parse(x.Groups[3].Value))
.Select(x => string.Format("{0}-{1}-{2}", x.Groups[1], x.Groups[2], x.Groups[3]));
foreach (string x in query)
Console.WriteLine(x);
}
}
}
41123562XXX-0730-66
4345002XXX-0920-50
411002XXX-0505-33
411252XXX-0312-13
434202XXX-0104-3
Press any key to continue . . . --------------------编程问答-------------------- string[] ary = @"1=411002XXX,0505,北京丰台区,1,1,33,1,1
2=411252XXX,0312,北京丰台区,1,1,13,1,1
3=41123562XXX,0730,北京丰台区,1,1,66,1,1
4=4345002XXX,0920,北京丰台区,1,1,50,1,1
5=434202XXX,0104,北京丰台区,1,1,3,1,1".Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
ary = ary.OrderByDescending(t => Convert.ToInt32(Regex.Match(t, @"(?<=^([^,]+,){5})\d+").Value))
.Select(t => Regex.Replace(t, @"\d+=([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),\S+$","$1-$2-$6")).ToArray();
--------------------编程问答-------------------- Regex regex = new Regex(@"(?m)^\d+=([^,]+),([^,]+),(?:[^,]+,){3}([^,]+)(?:,\d+){2}");
MatchCollection collection = regex.Matches(input);
foreach (Match item in collection.Cast<Match>().OrderByDescending(s => Convert.ToInt32(s.Groups[3].Value)))
{
Console.WriteLine("{0}-{1}-{2}", item.Groups[1].Value, item.Groups[2].Value, item.Groups[3].Value);
} --------------------编程问答-------------------- 除
补充:.NET技术 , C#