Sunday, March 27, 2011

Java Problem: Returning a string entered as reverse text

Hi,

I'm trying to make a method that returns a string of words in opposite order.

IE/ "The rain in Spain falls mostly on the" would return: "the on mostly falls Spain in rain The"

for this i am not supposed to use any built in Java classes just basic java

So far i have:

    lastSpace = stringIn.length(); 

    for (int i = stringIn.length() - 1; i >= 0; i--){
        chIn = stringIn.charAt(i);
        if (chIn == ' '){
            word = stringIn.substring(i + 1, lastSpace);
            stringOut.concat(word);
            lastS = i;
        }
    }
    word = stringIn.substring(0,lastSpace);
    stringOut.concat(word);

    return stringOut;

My problem is when stringOut is returned to its caller it always is a blank string.

Am i doing something wrong? Maybe my use of string.concat()?

Any help would be much appreciated. Thank you

From stackoverflow
  • In Java, Strings are immutable, i.e. they can't be changed. concat() returns a new string with the concatenation. So you want something like this:

    stringOut = stringOut.concat(word);
    

    or

    stringOut += word
    

    as Ray notes, there are more succinct ways to do this though.

  • That's because you need to assign the return of concat to something:

    stringOut=stringOut.concat(word)
    

    Strings in Java (and .net) are immutable.

  • You would do better if you use the indexOf method of String class, rather than that loop to find each space.

  • I felt like coding , so here you go :

    
    import java.util.*;
    
    class ReverseBuffer {
        private StringBuilder soFar;
        public ReverseBuffer() {
            soFar = new StringBuilder();
        }
    
        public void add(char ch) {
            soFar.append(ch);
        }
    
        public String getReversedString() {
            String str = soFar.toString();
            soFar.setLength(0);
            return str;
        }
    }
    
    public class Reverso {
        public static String[] getReversedWords(String sentence) {
            ArrayList < String > strings = new ArrayList < String >();
            ReverseBuffer rb = new ReverseBuffer();
            for(int i = 0;i < sentence.length();i++) {
                char current = sentence.charAt(i);
                if(current == ' ') {
                    strings.add(rb.getReversedString());
                }
                else {
                    rb.add(current);
                }
            }
            strings.add(rb.getReversedString());
            Collections.reverse(strings);
            return (String[])strings.toArray(new String[0]);
        }
    
        public static void main(String[] args) {
            String cSentence = "The rain in Spain falls mostly on the";
            String words[] = Reverso.getReversedWords(cSentence);
            for(String word : words) {
                System.out.println(word);
            }
        }
    }
    

    EDIT: had to call getReversedString once more after the loop.

    Hope this helps !

  • public String reverseWords(String words)
    {
      if(words == null || words.isEmpty() || !words.contains(" "))
        return words;
    
      String reversed = "";
      for(String word : words.split(" "))
        reversed = word + " " + reversed;
    
      return reversed;
    }
    

    Only API used is String (which should be allowed when manipulating Strings...)

0 comments:

Post a Comment