Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation in alternating order

Tags:

string

c#

linq

I have a string

string value = "123456789";

now I need to re-arrange the string in the following way:

123456789
1       right 
12      left 
312     right 
3124    left 
53124   right 
...
975312468 result

Is there a fancy linq one liner solution to solve this?

My current (working but not so good looking) solution:

string items = "abcdefgij";
string result = string.Empty;
for (int i = 0; i < items.Length; i++)
{
    if (i % 2 != 0)
    {
        result = result + items[i];
    }
    else
    {
        result = items[i] + result;
    }
}
like image 972
Impostor Avatar asked Dec 05 '22 17:12

Impostor


2 Answers

string value = "123456789";
bool b = true;
string result = value.Aggregate(string.Empty, (s, c) =>
{
    b = !b;
    return b ? (s + c) : (c + s);
});    

I actually don't like local variables inside LINQ statements, but in this case b helps alternating the direction. (@klappvisor showed how to live without b).

like image 72
René Vogt Avatar answered Dec 08 '22 10:12

René Vogt


You can use length of the res as variable to decide from which side to append

items.Aggregate(string.Empty, (res, c) => res.Length % 2 == 0 ? c + res : res + c);

Alternative solution would be zipping with range

items.Zip(Enumerable.Range(0, items.Length), (c, i) => new {C = c, I = i})
    .Aggregate(string.Empty, (res, x) => x.I % 2 == 0 ? x.C + res : res + x.C)

EDIT: don't really needed ToCharArray...

like image 21
klappvisor Avatar answered Dec 08 '22 11:12

klappvisor