0
using System;
using System.Linq;

namespace Array.ReversingArrayChar
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            char[] symbol = input.Split(' ').Select(char.Parse).ToArray();
            symbol.Reverse();
            for (int a = 0; a <= symbol.Length - 1; a++)
            {
                Console.Write(symbol[a] + " ");
            }
        }
    }
}
    

When I run the code I get the Array printed but not in reversed order even tho I used .Reverse(). It's probably a really simple mistake but it's too late at night for my brain to figure it out.

Kurubaran
  • 8,696
  • 5
  • 43
  • 65
  • you should implement a reverse for. – Felipe Esteves Sep 01 '22 at 15:46
  • 4
    Read the documentation for Linq's `Reverse` method carefully. Very carefully. What does it say it does _precisely_? Hint: It is not reversing the array itself. It [**returns**](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.reverse?view=net-6.0#returns) "_A sequence whose elements correspond to those of the input sequence in reverse order._". –  Sep 01 '22 at 15:47
  • FYI `Split` is going to return a string array and the only way char.Parse is going to work is if each string in that array is exactly one character. So it would work for "a b c", but not "abc" – juharr Sep 01 '22 at 15:51

2 Answers2

4

Enumerable.Reverse is a LINQ extension that returns the sequence reversed, so you have to assign it to a variable. But here you want to use Array.Reverse:

Array.Reverse(symbol);

Use Enumerable.Reverse if you don't want to modify the original collection and if you want to support any kind of sequence. Use List.Reverse or Array.Reverse if you want to support only these collections and you want to modify it directly. Of course this is more efficient since the method knows the size and you need less memory.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Oh Man..! you are almost there, your code is fine but you need to use the output of the .Reverse() method. since the method won't modify the actual collection, it will return the reversed array. you can try the following:

string input = "A S D R F V B G T";
char[] symbols = input.Split(' ').Select(char.Parse).ToArray();
foreach (var symbol in symbols.Reverse())
{
    Console.Write(symbol + " ");
}

You will get the output as T G B V F R D S A

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88