INTRODUCTION
- We are all mostly using the predefined function for string reversal and we can't know how it works in the background to reverse a string or letter.
- Now, I am going to explain how to print a string or letters in reverse without using the predefined function in the C# programming language.
- If asked by the interviewer to write a program for reversing a string using the predefined function in .NET, a lot of candidates get confused because we mostly use the predefined functions only.
What is a Reverse String?
- The string is a sequence of characters.
- Reverse a string is used to change the position of characters of the string.
Example
- Input String is: Corner
- Reverse String is: renroC
REQUIREMENTS
- Visual Studio
- Console Application
STEP 1
Open Visual Studio and choose File->New->Project. Then, the "New Project" window will appear on the screen.
STEP 2
Next, to choose the Visual C# -> Console application, then give the name of your application in the New Project window, then browse the location for your project. After that, press the OK button to create your console application.
After that, write the code for string reversal.
Program for reversing a string using the predefined function
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace StringFunctions
- {
- class Program
- {
- class stringFunction
- {
- public string StringReverse(string input)
- {
- char[] array = input.ToCharArray();
- Array.Reverse(array);
- return new string(array);
- }
-
- }
- static void Main(string[] args)
- {
- stringFunction obj = new stringFunction();
- Console.WriteLine("Enter the string for String Reverse:");
- string strRev=Console.ReadLine();
- Console.WriteLine("Output:");
- Console.Write(obj.StringReverse(strRev));
- Console.ReadKey();
- }
- }
- }
Save and run the program to get the output.
OUTPUT
Program for reversing a string without using the pre-defined function
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- public string reverse(string input)
- {
- string strreverse="";
- int len = input.Length-1;
- for (int i = len; i >= 0;i-- )
- {
- strreverse += input[i];
- }
-
- return (strreverse);
- }
- static void Main(string[] args)
- {
-
- Program obj = new Program();
- Console.WriteLine("*****Without Using The Predefined Function******");
- Console.WriteLine("Enter the String to Reverse:");
- string strRev = Console.ReadLine();
- Console.WriteLine("output:");
- Console.Write(obj.reverse(strRev));
- Console.ReadKey();
-
- }
- }
- }
Save and run the program to get the output.
Conclusion
I hope that after reading this blog, you all know how to reverse a string or letter with and without a predefined function in C# programming language.