Pages

Saturday, April 27, 2013

C#: Reverse a Sentence using Stack

//declare a string to store the splitted characters
string str=null;
//declare a string array to store splitted words
string[] splitStr = null;
//declare a Stack with generic integer type
Stack<string> strArr = new Stack<string>();

public void StackReversal(string s)
{
//split the words using space delimiter
splitStr=s.Split(' ');


//Iterate each character in the sentence
foreach (char ch in s)
{

//Check if character is space or it reaches the last character in the sentence.   
if (ch.Equals(' ')||s[s.Length-1]==ch)
{

//Last character in the sentence is reached
if (s[s.Length - 1] == ch)
{
//join the characters to form a string
str = str + ch;
//add the string to stack
strArr.Push(str);
//exit the loop since end of sentence
break;
}

//if not end of sentence
strArr.Push(str);
// add string to stack
strArr.Push(" ");
//for joining the next string
str = null;
}
str = str + ch;
}
//get the stack count
int c = strArr.Count;
//loop through all items in stack and display in LIFO manner
for(int i=0; i<c;i++)
{
Console.Write(strArr.Pop());
}
Console.WriteLine();
}

//input string: "This is a sentence"
Output: sentence a is This


No comments:

Post a Comment