题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
先将所有的字母提取出来放进一个list里 然后对list进行排序,这里使用linq无视大小写 然后对chars进行遍历,是字母的依次替换为list中的元素,不是字母的正常拼接
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppTest
{
public static class Test
{
public static void Main()
{
string input = Console.ReadLine();
char[] chars = input.ToCharArray();
List<char> list = new List<char>();
foreach (char c in chars)
{
if (char.IsLetter(c))
{
list.Add(c);
}
}
list = list.OrderBy(x => char.ToLower(x)).ToList();
StringBuilder sb = new StringBuilder();
int index = 0;
for (int i = 0; i < chars.Length; i++)
{
if (char.IsLetter(chars[i]))
{
sb.Append(list[index++]);
}
else
{
sb.Append(chars[i]);
}
}
Console.WriteLine(sb.ToString());
}
}
}