Can you reverse order a string in one line with LINQ or a LAMBDA expression

前端 未结 11 902
暗喜
暗喜 2021-02-02 16:01

Not that I would want to use this practically (for many reasons) but out of strict curiousity I would like to know if there is a way to reverse order a string using LINQ and/or

11条回答
  •  时光取名叫无心
    2021-02-02 16:11

    public static string Reverse(string word)
    {
       int index = word.Length - 1;
       string reversal = "";
    
       //for each char in word
       for (int i = index; index >= 0; index--)
       {
           reversal = reversal + (word.Substring(index, 1));
           Console.WriteLine(reversal);
       }
       return reversal;
    }
    

    Quite simple. So, from this point on, I have a single method that reverses a string, that doesn't use any built-in Reverse functions.

    So in your main method, just go,

    Console.WriteLine(Reverse("Some word"));

    Technically that's your one liner :P

提交回复
热议问题