Monday, April 07, 2008

reverse the words in a sentence using C# (managed code)

Note: The assumption here is that the words are delimited by a single space. This program could be easily modified to work for multiple spaces in the sentence.

Code snippet:

using System;
using System.Collections;

public class Reversal
    public string Reverse(string words)
        //find each word and push it in to stack.
        Stack myStack = new Stack();
        //count the number of the spaces in the sentence.
        StringBuilder sb = new StringBuilder();
        int size = 0;

        //get the total # of words by using delimiter ' '
        for(int i = 1; i < words.Length -1 ; i++)
            if(words[i] == ' ')

        //temp string
        string [] temp = new string [size];
        //split the words using delimiter " "
        temp = words.Split(' ');

        //push all the words from the begining in to
        //the stack except for the last word
        for (int i = 0; i < size; i++)

        //take care of the last word
        int lastOccuranceOfSpace = words.LastIndexOf(' ');

        //get the last word from the input.
        String lastWord = words.Substring(++lastOccuranceOfSpace);
        //push the last word

        //pop the stack as you will get the items in reverse order
        for (int i = 0; i < size+1; i++)
            string tmp = myStack.Pop();
            StringBuilder sb1 = new StringBuilder();
            //reverse each word you get
            for (int j = tmp.Length - 1; j >= 0; j--)
            sb1.Append(" ");
            //add it to the final string

    //now sb contains the input in reverse order
    return sb.ToString();

class Program
    static void Main(string[] args)
        Reversal r = new Reversal();
        string reversedString = r.Reverse("hello this is ram's code");
        System.Console.WriteLine("The reversed string is:" + reversedString);


Anonymous said...

StringBuilder sb = new StringBuilder();
var a = "three four five".Split(' ').Reverse();
foreach(var b in a)
sb.Append(' ' + b);
string d = sb.ToString();

Ram Alagianambi said...

The main intention for writing a lengthy code is to show how to do the reverse words in C# similar to C++, these used to be common among intv. qns in the past.