开发者

Splitting a string at every character

开发者 https://www.devze.com 2023-03-13 18:45 出处:网络
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 co

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

精彩评论

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