Easy way to reverse each word in a sentence

后端 未结 9 2213
深忆病人
深忆病人 2021-01-02 12:59

Example:

string str = \"I am going to reverse myself.\";
string strrev = \"I ma gniog ot esrever .flesym\"; //An easy way to achieve this

A

9条回答
  •  隐瞒了意图╮
    2021-01-02 13:13

    Well, here's a LINQ solution:

    var reversedWords = string.Join(" ",
          str.Split(' ')
             .Select(x => new String(x.Reverse().ToArray())));
    

    If you're using .NET 3.5, you'll need to convert the reversed sequence to an array too:

    var reversedWords = string.Join(" ",
          str.Split(' ')
             .Select(x => new String(x.Reverse().ToArray()))
             .ToArray());
    

    In other words:

    • Split on spaces
    • For each word, create a new word by treating the input as a sequence of characters, reverse that sequence, turn the result into an array, and then call the string(char[]) constructor
    • Depending on framework version, call ToArray() on the string sequence, as .NET 4 has more overloads available
    • Call string.Join on the result to put the reversed words back together again.

    Note that this way of reversing a string is somewhat cumbersome. It's easy to create an extension method to do it:

    // Don't just call it Reverse as otherwise it conflicts with the LINQ version.
    public static string ReverseText(this string text)
    {
        char[] chars = text.ToCharArray();
        Array.Reverse(chars);
        return new string(chars);
    }
    

    Note that this is still "wrong" in various ways - it doesn't cope with combining characters, surrogate pairs etc. It simply reverses the sequence of UTF-16 code units within the original string. Fine for playing around, but you need to understand why it's not a good idea to use it for real data.

提交回复
热议问题