[英]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:我想要做的是按字母顺序对这个字符串进行排序,如下所示:
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:您可以尝试查询给定的字符串:
','
to have separated words','
以分隔单词Trim()
.Trim()
的帮助下去掉空格和引号。word
sword
sGroup
words by the 1st lettersGroup
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
使用
Split
和Join
的方法
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.