能否使用 LINQ 或 LAMBDA 表达式对一行中的字符串进行反向排序

发布于 2024-07-27 12:19:42 字数 345 浏览 2 评论 0原文

并不是说我想实际使用它(出于多种原因),而是出于严格的好奇心,我想知道是否有一种方法可以在一行代码中使用 LINQ 和/或 LAMBDA 表达式来反转字符串的顺序。 /strong>,不使用任何框架“反向”方法。

例如

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

,reverseValue 将导致“em esrever”

编辑 显然这是一个不切实际的问题/解决方案,我知道这一点,所以不用担心,这只是围绕 LINQ/LAMBDA 构造的好奇问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

很酷不放纵 2024-08-03 12:19:42

好吧,即使不使用 LINQ 或 lambda,我也可以在很长的一行中完成此操作:(

string original = "reverse me"; char[] chars = original.ToCharArray(); char[] reversed = new char[chars.Length]; for (int i=0; i < chars.Length; i++) reversed[chars.Length-i-1] = chars[i]; string reversedValue = new string(reversed);

亲爱的潜在编辑:不要将其展开到多行中。重点是它是一行,根据上面的句子和问题。)

但是,如果我看到有人为此避免使用框架方法,我会质疑他们的理智。

请注意,这根本不使用 LINQ。 LINQ 的答案是:

string reverseValue = new string(original.Reverse().ToArray());

避免使用 Reverse,而是使用 OrderByDescending 代替:

string reverseValue = new string(original.Select((c, index) => new { c, index })
                                         .OrderByDescending(x => x.index)
                                         .Select(x => x.c)
                                         .ToArray());

Blech。 不过我喜欢迈赫达德的回答。 当然,所有这些方法的效率都远低于直接方法。

哦,他们也都错了。 反转字符串比反转代码点的顺序更复杂。 考虑组合字符、代理对等......

Well, I can do it in one very long line, even without using LINQ or a lambda:

string original = "reverse me"; char[] chars = original.ToCharArray(); char[] reversed = new char[chars.Length]; for (int i=0; i < chars.Length; i++) reversed[chars.Length-i-1] = chars[i]; string reversedValue = new string(reversed);

(Dear potential editors: do not unwrap this onto multiple lines. The whole point is that it's a single line, as per the sentence above it and the question.)

However, if I saw anyone avoiding using framework methods for the sake of it, I'd question their sanity.

Note that this doesn't use LINQ at all. A LINQ answer would be:

string reverseValue = new string(original.Reverse().ToArray());

Avoiding using Reverse, but using OrderByDescending instead:

string reverseValue = new string(original.Select((c, index) => new { c, index })
                                         .OrderByDescending(x => x.index)
                                         .Select(x => x.c)
                                         .ToArray());

Blech. I like Mehrdad's answer though. Of course, all of these are far less efficient than the straightforward approach.

Oh, and they're all wrong, too. Reversing a string is more complex than reversing the order of the code points. Consider combining characters, surrogate pairs etc...

手心的温暖 2024-08-03 12:19:42

我认为这没有实际用途,只是为了好玩:

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())

I don't see a practical use for this but just for the sake of fun:

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())
清醇 2024-08-03 12:19:42
new string(value.Reverse().ToArray())
new string(value.Reverse().ToArray())
温柔女人霸气范 2024-08-03 12:19:42
var reversedValue = value.ToCharArray()
                         .Select(ch => ch.ToString())
                         .Aggregate<string>((xs, x) => x + xs);
var reversedValue = value.ToCharArray()
                         .Select(ch => ch.ToString())
                         .Aggregate<string>((xs, x) => x + xs);
北座城市 2024-08-03 12:19:42

具有递归 lambda 的变体:

  var value = "reverse me";
  Func<String, String> f = null; f = s => s.Length == 1 ? s : f(s.Substring(1)) + s[0]; 
  var reverseValue = f(value);

LP,
德扬

Variant with recursive lambda:

  var value = "reverse me";
  Func<String, String> f = null; f = s => s.Length == 1 ? s : f(s.Substring(1)) + s[0]; 
  var reverseValue = f(value);

LP,
Dejan

把人绕傻吧 2024-08-03 12:19:42

您可以使用 Aggregate 将每个 Char 添加到反转字符串之前:

 "reverse me".Aggregate("", (acc, c) => c + acc);

You can use Aggregate to prepend each Char to the reversed string:

 "reverse me".Aggregate("", (acc, c) => c + acc);
不可一世的女人 2024-08-03 12:19:42
var reversedValue= "reverse me".Reverse().ToArray();
var reversedValue= "reverse me".Reverse().ToArray();
梦过后 2024-08-03 12:19:42

除了之前的一篇文章之外,这里还有一个性能更高的解决方案。

var actual0 = "reverse me".Aggregate(new StringBuilder(), (x, y) => x.Insert(0, y)).ToString();

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();
葵雨 2024-08-03 12:19:42
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;
}

非常简单。 因此,从现在开始,我有一个反转字符串的方法,该方法不使用任何内置的 Reverse 函数。

因此,在您的主要方法中,只需执行

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

从技术上讲,这就是您的单行代码:P

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

丶视觉 2024-08-03 12:19:42

如果我们需要支持组合字符和代理项对:

// 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

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 ???? and the ???? should be preserved, not corrupted.

var value = "reverse me"; // or "Not nai\u0308ve.", or "The sphere \U0001D54A and the torus \U0001D54B.". 

var list = new List<string>(value.Length);

var enumerator = StringInfo.GetTextElementEnumerator(value);
while (enumerator.MoveNext())
{
  list.Add(enumerator.GetTextElement());
}
list.Reverse();

var result = string.Concat(list);

Documentation: MSDN: System.Globalization.StringInfo Class

你的他你的她 2024-08-03 12:19:42
string str="a and b";
string t="";

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

foreach (char c in schar )
{
    test += c.ToString();
}
string str="a and b";
string t="";

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

foreach (char c in schar )
{
    test += c.ToString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文