String program #4
(Reverse
string)
Enter string: manish gautam
Reverse string using in-built
function: matuag hsinam
Reverse string word by word: hsinam
matuag
Reverse complete sentence: matuag
hsinam
The program for the string program is
written in C# programming language and will accept a string as input. The loops
will iterate based on the entry of string, reverse the string and return the
output. We can reverse the input string in 3 ways:
1.
Using
in-built function
2.
Word
by word
3.
Completer
sentence
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.String
{
class String4 //reverse string
{
static void Main(string[] args)
{
Console.Write("Enter string: ");
string str = Console.ReadLine();
/*Method1: (Using In-built Reverse function)*/
char[]
ch = str.ToCharArray();
Array.Reverse(ch);
string reversedString = new string(ch);
Console.WriteLine("Reverse string using in-built function: " + reversedString);
/*Method2: (Using in-built function that reverse word by
word)*/
Console.WriteLine("Reverse string word by word: " + PrintWordsInReverse(str));
/*Method3: (Using in-built function that reverse complete
sentence)*/
Console.WriteLine("Reverse complete sentence: " +
PrintSentenceInReverse(str));
Console.ReadKey();
}
static string PrintWordsInReverse(string str)
{
string revWord = string.Empty;
string finalSentance = string.Empty;
for
(int i = 0; i < str.Length;
i++)
{
if (str[i] != ' ')
{
revWord = str[i] + revWord;
}
else
{
revWord = revWord + ' ';
finalSentance =
finalSentance + revWord;
revWord = string.Empty;
}
}
if
(revWord != string.Empty)
finalSentance = finalSentance +
revWord;
return finalSentance;
}
public static string PrintSentenceInReverse(string str1)
{
int
i, j = 0;
char
temp;
char[]
str = new char[100];
str = str1.ToCharArray();
i = 0;
j = str.Length - 1;
while
(i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
return new string(str);
}
}
}
Output:
The input
string1 here is “manish gautam”. So, program will return the reverse string in
all the 3 cases. The output is shown below:
Enter string: manish gautam
Reverse string using in-built function: matuag
hsinam
Reverse string word by word: hsinam matuag
Reverse complete sentence: matuag hsinam
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table String based program
Keep learning and sharing...
No comments:
Post a Comment