I want to print string in reverse format:
Input: My name is Archit Patel
Output: Patel Archit is name My
.
I\'ve tied the
this.lblStringReverse.Text = Reverse(this.txtString.Text);
private int NoOfWhiteSpaces(string s)
{
char[] sArray = s.ToArray<char>();
int count = 0;
for (int i = 0; i < (sArray.Length - 1); i++)
{
if (sArray[i] == ' ') count++;
}
return count;
}
private string Reverse(string s)
{
char[] sArray = s.ToArray<char>();
int startIndex = 0, lastIndex = 0;
string[] stringArray = new string[NoOfWhiteSpaces(s) + 1];
int stringIndex = 0, whiteSpaceCount = 0;
for (int x = 0; x < sArray.Length; x++)
{
if (sArray[x] == ' ' || whiteSpaceCount == NoOfWhiteSpaces(s))
{
if (whiteSpaceCount == NoOfWhiteSpaces(s))
{
lastIndex = sArray.Length ;
}
else
{
lastIndex = x + 1;
}
whiteSpaceCount++;
char[] sWordArray = new char[lastIndex - startIndex];
int j = 0;
for (int i = startIndex; i < lastIndex; i++)
{
sWordArray[j] = sArray[i];
j++;
}
stringArray[stringIndex] = new string(sWordArray);
stringIndex++;
startIndex = x+1;
}
}
string result = "";
for (int y = stringArray.Length - 1; y > -1; y--)
{
if (result == "")
{
result = stringArray[y];
}
else
{
result = result + ' ' + stringArray[y];
}
}
return result;
}
public static string MethodExercise14Logic(string str)
{
string[] sentenceWords = str.Split(' ');
Array.Reverse(sentenceWords);
string newSentence = string.Join(" ", sentenceWords);
return newSentence;
}
"please send me the code of this program."
Okay ...
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string text = "My name is Archit Patel";
Console.WriteLine(string.Join(" ", text.Split(' ').Reverse()));
}
}
Now: what have you learned?
Also, as Guffa points out, for versions below .Net 4.0 you'll need to add .ToArray()
since string.Join doesn't have the correct overload in those versions.
I appreciate Rob Anderson answer, but it will reverse complete sentence, Just editing that
string s = "My name is Archit Patel";
string[] words = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (int i = words.Length - 1; i >= 0; i--)
{
sb.Append(words[i]);
sb.Append(" ");
}
Console.WriteLine(sb);
O/P will be "Patel Archit is name My"