Yulia Genova
Yulia Genova

Reputation: 49

How to reverse the digits INSIDE of an element in an array in C#

here is what I try to accomplish in C#: Before reverse:

new string[] initial={"1011","001"};

After reverse:

new string[] final={"1101","100"};

Any idea how to do this?

Upvotes: 0

Views: 309

Answers (5)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26675

As you know the string type represents a sequence of Unicode characters. And we can select reversed sequence of string object with the help of IEnumerable.Reverse() method. And the last remaining thing is to use Select() method to project each element of an array into a new form:

 var final = initial.Select(x => new string(x.Reverse().ToArray())).ToArray();

The inputs: 35, 001, abcd
The output: 53, 100, dcba

Upvotes: 1

Masoud Mohammadi
Masoud Mohammadi

Reputation: 1749

because it is unclear that you want to reverse the array, or reverse all of it's elements. i have covered both.

if you want to reverse all elements inside array:

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] x = new string[] {"1100", "2200"};
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = new string(x[i].Reverse().ToArray());
            }
            foreach (string s in x)
            {
                Console.WriteLine(s);
            }
        }
    }
}

result: "0011", "0022"

if you want to reverse the array to show from last to the first:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] x = new string[] {"1100", "2200"};
            Array.Reverse(x);
            foreach (string s in x)
            {
                Console.WriteLine(s);
            }
        }
    }
}

result: "2200" ,"1100"

Upvotes: 1

yi.han
yi.han

Reputation: 379

In place reverse:

Array.Reverse(array);

Return new array:

var reversed = array.Reverse().ToArray();

Upvotes: 0

Durgpal Singh
Durgpal Singh

Reputation: 11983

you can use Reverse method of array like this.

Array.Reverse(array_name);

for more details see this

https://msdn.microsoft.com/en-us/library/d3877932(v=vs.110).aspx

Upvotes: 0

user1726343
user1726343

Reputation:

If you have an enumerable original of enumerables, and you want to project it into an enumerable that contains the same members, only reversed, you can use:

var reversedMembers = original.Select(Enumerable.Reverse);

If you are specifically concerned with string arrays, you can do this:

var original = new string[] { "1011","1101" };
var reversed = original.Select(s => String.Concat(s.Reverse())).ToArray();

Upvotes: 3

Related Questions