简体   繁体   English

使用第一个字母对字符串进行排序

[英]Sorting string with its first letter

I have following string我有以下字符串

string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";

What I am trying to do is to sort this string alphabetically like this:我想要做的是按字母顺序对这个字符串进行排序,如下所示:

  • Brown棕色的
  • Johnson Jones约翰逊琼斯
  • Williams威廉姆斯

I have no idea what to do and how to solve this.我不知道该怎么做以及如何解决这个问题。 What should I do with it我该怎么办

You can try querying the given string:您可以尝试查询给定的字符串:

  • Split on ',' to have separated words拆分','以分隔单词
  • Get rid of spaces and quotation marks with a help of Trim() .Trim()的帮助下去掉空格和引号。
  • Order the word s排序word s
  • As I can see you want to Group words by the 1st letters如我所见,您想按第一个字母对单词进行Group
  • Finally, lets materialize the result as an array最后,让我们将结果具体化为一个数组

Code:代码:

  string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";

  string[] result = strings
    .Split(',')
    .Select(word => word.Trim(' ', '"'))
    .Where(word => !string.IsNullOrEmpty(word))
    .OrderBy(word => word)
    .GroupBy(word => word[0])
    .Select(group => string.Join(" ", group))
    .ToArray();

If you want to obtain string instead of array, put Join :如果要获取string而不是数组,请输入Join

  string myString = string.Join(" ", result);

Let's have a look:我们来看一下:

  Console.Write(string.Join(Environment.NewLine, result));

Output:输出:

Brown
Johnson Jones
Will

Approach with Split and Join使用SplitJoin的方法

string strings = "\"Johnson\", \"Williams\", \"Brown\", \"Jones\"";
string result = string.Join(", ", strings.Split().Select(x => x.Trim(',')).OrderBy(x => x));

Assuming you are using a list with multiple strings, we can use a bubble sorting algorithm to sort the list.假设您使用的是包含多个字符串的列表,我们可以使用冒泡排序算法对列表进行排序。

Loop through the list swapping positions if the second string has a lower letter than the first one.如果第二个字符串的字母低于第一个字符串,则循环遍历列表交换位置。 Loop until the list is fully sorted.循环直到列表完全排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM