Easy way to reverse each word in a sentence

后端 未结 9 2222
深忆病人
深忆病人 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:07

    To reverse a string I use:

    new String( word.Reverse().ToArray() )
    

    The Reverse() function is part of LINQ and works because String implements IEnumerable. Its result is another IEnumerable which now needs to be converted to string. You can do that by calling ToArray() which gives a char[] and then pass that into the constructor of string.

    So the complete code becomes:

    string s="AB CD";
    string reversed = String.Join(" ",
        s.Split(' ')
         .Select(word => new String( word.Reverse().ToArray() ) ));
    

    Note that this code doesn't work well with certain unicode features. It has at least two problems:

    1. Unicode characters outside the basic plane need two chars when UTF-16 encoded. Reversing them breaks the encoding. This is relatively easy to fix since there are just a limited number of characters initiation such a sequence(16 if I remember correctly) and this most likely won't be extended in future unicode versions.
    2. Binding character sequences. For example it's possible to create accented characters by writing the base character and a binding accent behind it. This problem is hard to work around since new combining characters can be added with future unicode versions.

提交回复
热议问题