Eno*_*noy 2 c# arrays sorting string alphabetical
1) 有一个 Kata 说明对字符串数组中的所有字符串进行排序,然后取第一个单词并在每个字母之间添加 ***:https : //www.codewars.com/kata/sort-and-star
2)例如:
(1) 给出:
bitcoin
take
over
the
world
maybe
who
knows
perhaps
Run Code Online (Sandbox Code Playgroud)
(2) 订购后:
bitcoin
knows
maybe
over
perhaps
take
the
who
world
Run Code Online (Sandbox Code Playgroud)
(3)返回结果为:
b***i***t***c***o***i***n
Run Code Online (Sandbox Code Playgroud)
3)但是我面临的困难如下:我们如何表达“以大写字母开头的单词先排序”?
4)我尝试了以下代码:
using System;
public class Kata
{
public static string TwoSort(string[] s)
{
foreach(string str in s){
Console.WriteLine(str);
}
Console.WriteLine("");
Array.Sort(s);
foreach(string str in s){
Console.WriteLine(str);
}
Console.WriteLine("");
string firstWord = s[0];
string result = "";
foreach(char letter in firstWord){
result += letter + "***";
}
Console.WriteLine(result.Substring(0, result.Length - 3));
return result.Substring(0, result.Length - 3);
}
}
Run Code Online (Sandbox Code Playgroud)
5)例如:
(1) 给出如下数组:
Lets
all
go
on
holiday
somewhere
very
cold
Run Code Online (Sandbox Code Playgroud)
(2) 订购后:
all
cold
go
holiday
Lets
on
somewhere
very
Run Code Online (Sandbox Code Playgroud)
(3) 当前错误结果:
a***l***l
Run Code Online (Sandbox Code Playgroud)
(4) 预期正确结果:
L***e***t***s
Run Code Online (Sandbox Code Playgroud)
我也读过:
您应该指定比较器,例如(Linq解决方案):
string[] source = new string[] {
"Lets",
"all",
"go",
"on",
"holiday",
"somewhere",
"very",
"cold",
};
// StringComparer.Ordinal: order by Ascii values; capital letters < small letters
var ordered = source
.OrderBy(item => item, StringComparer.Ordinal);
Console.Write(string.Join(", ", ordered));
Run Code Online (Sandbox Code Playgroud)
结果:
Lets, all, cold, go, holiday, on, somewhere, very
Run Code Online (Sandbox Code Playgroud)
要获得所需的结果(如果您坚持订购),您可以将
var result = string.Join("***", source
.OrderBy(item => item, StringComparer.Ordinal)
.First()
.Select(c => c)); // <- turn string into IEnumerable<char>
Console.Write(result);
Run Code Online (Sandbox Code Playgroud)
结果:
L***e***t***s
Run Code Online (Sandbox Code Playgroud)
如果您想继续使用当前代码,请更改Array.Sort(s);为
Array.Sort(s, StringComparer.Ordinal);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4267 次 |
| 最近记录: |