How to reverse the words in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pinman
    New Member
    • Aug 2008
    • 20

    How to reverse the words in a string

    I am trying to reverse the location of words in a string which i have working but not sure if it's the best way. I can't use Array.Reverse or String.Split in the code. The idea is to return a string with the words reversed. eg: “The quick brown fox” should return “fox brown quick The”

    Code:
    public string ReverseWordsInString (string input)
        {
                   
            StringBuilder result = new StringBuilder();
                  
            //remove all potentially multiple whitespace from beginning
            //and end of string so indexof test does not match empty whitespace
            input = input.Trim();
            
            //next insert a single blank space at the end of the string 
            //to satisfy the last indexOf test.
            input = input.Insert((input.Length), " ");
            
            while(input != "")
            {
                //find location of whitespace to identify end of word
                int t = input.IndexOf(" ");
                
                //input the word into result string (use t + 1 to include the space)
                result.Insert( 0, (input.Substring(0 , (t + 1))));
                
                //removed the word just retrieved for the next loop
                input = input.Remove(0, (t + 1));
                t = 0;
            }
            return result.ToString();
        }

    Is it better to use stringbuilder for both operations for efficiency. Shall I cast the input string to a stringbuilder?

    Not sure if using a "while string not null" test is a good idea in the while loop. Also I would like to keep this to just 1 function answer.
    Last edited by Niheel; May 6 '10, 02:56 PM. Reason: punctuation, grammar, spelling
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    Originally posted by pinman
    hi i'm trying to reverse the location of words in a string which i have working but not sure if it's the best way. i can't use Array.Reverse or String.Split in the code. the idea is to return a string with the words reversed. eg: “The quick brown fox” should return “fox brown quick The”

    Code:
    public string ReverseWordsInString (string input)
        {
                   
            StringBuilder result = new StringBuilder();
                  
            //remove all potentially multiple whitespace from beginning
            //and end of string so indexof test does not match empty whitespace
            input = input.Trim();
            
            //next insert a single blank space at the end of the string 
            //to satisfy the last indexOf test.
            input = input.Insert((input.Length), " ");
            
            while(input != "")
            {
                //find location of whitespace to identify end of word
                int t = input.IndexOf(" ");
                
                //input the word into result string (use t + 1 to include the space)
                result.Insert( 0, (input.Substring(0 , (t + 1))));
                
                //removed the word just retrieved for the next loop
                input = input.Remove(0, (t + 1));
                t = 0;
            }
            return result.ToString();
        }

    is it better to use stringbuilder for both operations for efficiency. shall i cast the input string to a stringbuilder?
    not sure if using a "while string not null" test is a good idea in the while loop. any suggestions would be great thanks. also i would like to keep this to just 1 function answer.
    Because of the memory concerns you might want to change the input string to a StringBuilder class. From looking at the documentation the StringBuilder doesn't have a Trim function so you would have to do.

    StringBuilder sbInput = new StringBuilder(i nput.Trim());

    This would make your removal of the previous words more efficient.

    I don't believe the while string not null test would work though in your looping mechanism to remove words because presumably you a string or stringBuilder that has been allocated on the heap.

    I am not sure if the String Trim member function will throw an exception if it is given a null string, but you should be checking that yourself before your start your parsing.

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Have you considered using the .LastIndexOf function?

      Comment

      • pinman
        New Member
        • Aug 2008
        • 20

        #4
        The code works fine using the while loop as I've tested it with lots of input strings but I was just wondering if it was the best way of doing things by testing for a null string to end the loop and was thinking of a forloop maybe.

        I've used a stringbuilder for the "result" string and was thinking of doing the same thing for input string so thanks for letting me know about the trim and also for the test for a null input string.

        @Plater the lastindex of would give me the last position of the whitespace would it? So would I then take out the word beginning at this whitespace forward and then repeat?

        Comment

        • Plater
          Recognized Expert Expert
          • Apr 2007
          • 7872

          #5
          That was the idea i was going for. I hadn't really thought it through, just know that starting with the last word in the original is easier for what you are doing i think

          Comment

          • tlhintoq
            Recognized Expert Specialist
            • Mar 2008
            • 3532

            #6
            This is very obviously a school homework project.

            Bytes has a policy regarding assisting students with their homework.

            The short version is that the volunteers here can't help you with schoolwork.
            A) We don't know what material you have and have not learned in class.
            B) We don't know the guidelines you must follow.
            C) In the long run giving you the answers actually short changes your education.

            Hint 1: Try hitting Google with terms of your programming language and primary terms of what you want to do. For example "C# custom events" or "VB datagrid Excel". I've found this to be a very effective tool.
            Hint 2: Your text book
            Hint 3: Your instructor
            Hint 4: Posting guidelines regarding homework assignments.

            Comment

            Working...