Can you reverse order a string in one line with LI

2020-05-20 08:17发布

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 LAMBDA expressions in one line of code, without utilising any framework "Reverse" methods.

e.g.

string value = "reverse me";
string reversedValue = (....);

and reversedValue will result in "em esrever"

EDIT Clearly an impractical problem/solution I know this, so don't worry it's strictly a curiosity question around the LINQ/LAMBDA construct.

11条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-20 09:10

If we need to support combining characters and surrogate pairs:

// This method tries to handle:
// (1) Combining characters
// These are two or more Unicode characters that are combined into one glyph.
// For example, try reversing "Not nai\u0308ve.". The diaresis (¨) should stay over the i, not move to the v.
// (2) Surrogate pairs
// These are Unicode characters whose code points exceed U+FFFF (so are not in "plane 0").
// To be represented with 16-bit 'char' values (which are really UTF-16 code units), one character needs *two* char values, a so-called surrogate pair.
// For example, try "The sphere \U0001D54A and the torus \U0001D54B.". The                                                                     
查看更多
戒情不戒烟
3楼-- · 2020-05-20 09:11
string str="a and b";
string t="";

char[] schar = str.Reverse().ToArray();

foreach (char c in schar )
{
    test += c.ToString();
}
查看更多
够拽才男人
4楼-- · 2020-05-20 09:14
var reversedValue = value.ToCharArray()
                         .Select(ch => ch.ToString())
                         .Aggregate<string>((xs, x) => x + xs);
查看更多
甜甜的少女心
5楼-- · 2020-05-20 09:15
new string(value.Reverse().ToArray())
查看更多
迷人小祖宗
6楼-- · 2020-05-20 09:15

In addition to one previous post here is a more performant solution.

var actual0 = "reverse me".Aggregate(new StringBuilder(), (x, y) => x.Insert(0, y)).ToString();
查看更多
登录 后发表回答