MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Buy DVD

Reverse characters in a string

Write a C# program to print the characters in a string in the reverse order.

using System;
using System.Collections.Generic;
using System.Linq;


namespace SamplePrograms
{
    class ReverseCharacters
    {
        public static void Main()
        {
            // Prompt the user to enter the string
            Console.WriteLine("Please enter your string");


            // Read the user string from console
            string UserString = Console.ReadLine();


            // The simple way to reverse a string is to use
            // the built-in .net framework Reverse() function
            List<char> StringCharacters = UserString.Reverse().ToList();
            
            // Finally print each character from the collection
            foreach (char c in StringCharacters)
            {
                Console.Write(c);
            }


            Console.WriteLine();
            Console.ReadLine();
        }
    }
}


2 comments:

  1. It's more favorable to create a StringBuilder and append to it each character StringCharacters

    ReplyDelete
  2. i prefer this
    using System;

    namespace ReverseString
    {
    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Hello World!");
    string name = "Salman";

    for (int i = name.Length - 1; i >= 0; i--)
    {
    Console.Write(name[i]);
    }
    Console.ReadLine();

    }
    }
    }

    ReplyDelete