Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a char array in C#

Tags:

arrays

c#

char

I am trying to learn C#. I want to enter some text and for it to come out reversed. It reverses it, but multiple times, as many times as the inputted text is long. So hello comes out as olleholleholleholleholleh.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Reversed_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter text to be reversed");
            string inputText = Console.ReadLine();
            char[] myChar = inputText.ToCharArray();
            Array.Reverse(myChar);

            foreach (char character in myChar)
            {
                Console.Write(myChar);
            }
            Console.ReadLine();
        }
    }
}

I wanted to experiment with converting a string into a char array. Thought I would note this because yes I don't need the char array.

like image 800
WindowsProdigy7 Avatar asked Dec 25 '13 10:12

WindowsProdigy7


People also ask

How do you reverse an array in C?

printf("Array in reverse order: \n"); //Loop through the array in reverse order. for (int i = length-1; i >= 0; i--) { printf("%d ", arr[i]);


1 Answers

Because every time you write the whole array not a single character, try this:

 foreach (char character in myChar)
 {
     Console.Write(character);
 }
like image 154
Guru Stron Avatar answered Sep 30 '22 18:09

Guru Stron