String reversing in C# without using default function

Here we are going to discuss about two string reversing techniques.
 First of all we will check this question so our input string is "my name is tony" we need to revers it like this "tony is name my" how we can achieve it ??
string test="my name is c#";
string[] words = test.Split(' ');
so first we will split our string by space so we will get it by word  and insert that words into a string array.
so we have an array which is having value like this arr[0]=my,arr[1]=name etc.
so we will use a for loop and we will call the last index value first and print it and again it will decrement by 1 then next value until it reach us the index 0;
         
            for (int i = words.Length - 1; i >= 0; i--)
            {
                Console.Write(words[i] + " ");

            }
so finally we will get our string reversed like this "c# is name my"
In second string reverse technique  we will  simply pass the string and reverse it.  by default we can use  Array.Reverse(testarray) function  but we are not using that we will use custom method.
            string  revrs="androidsharp";
            char[] arr = revrs.ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int j = arr.Length - 1; j >= 0; j--)
            {
                sb.Append(arr[j]);

            }
            
            Console.WriteLine(sb.ToString());

Out Put:
prahsdiordna


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

namespace Shape
{
    class Array
    {
        public static void Main(string[] args)
        {
            //Method 1
            Console.WriteLine("Enter the String");
            string test = Console.ReadLine();
            string[] words = test.Split(' ');
            for (int i = words.Length - 1; i >= 0; i--)
            {
                Console.Write(words[i] + " ");

            }
            Console.WriteLine();

            //Method 2
            Console.WriteLine("Enter the String to reverse");
            string revrs = Console.ReadLine();
            char[] arr = revrs.ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int j = arr.Length - 1; j >= 0; j--)
            {
                sb.Append(arr[j]);

            }
            
            Console.WriteLine(sb.ToString());
        }

    }
}


0 comments: