I want to print string in reverse format:
Input: My name is Archit Patel
Output: Patel Archit is name My
.
I\'ve tied the
namespace Reverse_the_string
{
class Program
{
static void Main(string[] args)
{
// string text = "my name is bharath";
string text = Console.ReadLine();
string[] words = text.Split(' ');
int k = words.Length - 1;
for (int i = k;i >= 0;i--)
{
Console.Write(words[i] + " " );
}
Console.ReadLine();
}
}
}
public string GetReversedWords(string sentence)
{
try
{
var wordCollection = sentence.Trim().Split(' ');
StringBuilder builder = new StringBuilder();
foreach (var word in wordCollection)
{
var wordAsCharArray = word.ToCharArray();
Array.Reverse(wordAsCharArray);
builder.Append($"{new string(wordAsCharArray)} ");
}
return builder.ToString().Trim();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
string s = "this is a test";
string[] words = s.Split(' ');
StringBuilder sb = new StringBuilder();
for (int i = words.Length - 1; i >= 0; i--)
{
for (int j = words[i].Length -1; j >= 0;j--)
{
sb.Append(words[i][j]);
}
sb.Append(" ");
}
Console.WriteLine(sb);
This should do your job! OUTPUT: "Patel Archit is name My".
static void Main(string[] args)
{
string sentence = "My name is Archit Patel";
StringBuilder sb = new StringBuilder();
string[] split = sentence.Split(' ');
for (int i = split.Length - 1; i > -1; i--)
{
sb.Append(split[i]);
sb.Append(" ");
}
Console.WriteLine(sb);
Console.ReadLine();
}
If you want non-linq solution:
static string ReverseIntact(char[] input)
{
//char[] input = "dog world car life".ToCharArray();
for (int i = 0; i < input.Length / 2; i++)
{//reverse the expression
char tmp = input[i];
input[i] = input[input.Length - i - 1];
input[input.Length - i - 1] = tmp;
}
for (int j = 0, start = 0, end = 0; j <= input.Length; j++)
{
if (j == input.Length || input[j] == ' ')
{
end = j - 1;
for (; start < end; )
{
char tmp = input[start];
input[start] = input[end];
input[end] = tmp;
start++;
end--;
}
start = j + 1;
}
}
return new string(input);
}
You can use Stack for solving such queries:
String input = "My name is Archit Patel";
Stack<String> st = new Stack<String>();
for(String word : input.split(" "))
st.push(word);
Iterator it = st.iterator();
while(it.hasNext()){
System.out.print(st.pop()+" ");
}
Output String: "Patel Archit is name My"