开发者

Splitting a string at every character

let's say I have a string "hello world". I would like to end up with " dehllloorw". As I don't find any ready-made solution I thought: I can split the string into a character array, sort it and convert it back to a string.

In perl I can do s// but 开发者_C百科in .Net I'd have to do a .Split() but there's no overload with no parameters... if I do .Split(null) it seems to split by whitespace and .Split('') won't compile.

how do I do this (I hate to run a loop!)?


Array.Sort("hello world".ToCharArray());

Below is a quick demo console app

    class Program
    {
        static void Main(string[] args)
        {

            var array = "hello world".ToCharArray();

            Array.Sort(array);

            Console.WriteLine(new String(array));
            Console.ReadLine();
        }
    }


The characters in a string can be directly used, the string class exposed them as an enumeration - combine that with Linq / OrderBy and you have a one-liner to create the ordered output string:

string myString = "hello world";
string output = new string(myString.OrderBy(x => x).ToArray()); // dehllloorw


You could always do this:

private static string SortStringCharacters(string value)
{
    if (value == null)
        return null;
    return new string(value.ToList().Sort().ToArray());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜