简体   繁体   中英

Reversing the whole String and reversing each word in it

I have to write a code with two classes, one reverses a string changing positions eg

I love you becomes uoy evol I

and the other class reverses the string without changing positions eg

I love you becomes I evol uoy .

I have a small code but I have failed to get a way if calling the methods in those classes.

What I have now is just the code that reverses the string in the first way. Any help is welcome.

class StringReverse2{
    public static void main(String[] args){

        String string="I love you";
        String reverse = new StringBuffer(string).  //The object created through StringBuffer is stored in the heap and therefore can be modified
        reverse().toString();                       //Here the string is reversed

        System.out.println("Old String:"+string);   //Prints out I love you
        System.out.println("New String : "+reverse);//Prints out the reverse  that is "uoy evol I"
    }
}

I won't show you a full solution, but will guide you, here's one way to do that:

  • split the String according to spaces ( yourString.split("\\\\s+"); )
  • iterate on the resulted array and reverse each String (you can use the same method you use for your first task)
  • construct a new String from the array

There are many more solutions, visit the String API and fuel your creative fire!

you can just use the reverse() method on a StringBuilder object

public class Testf {
   public static void main(String[] args){

        String string="I love you";
        String reverse = new StringBuilder(string).reverse().toString();    

        StringBuilder secondReverse = new StringBuilder();
        for (String eachWord : string.split("\\s+")){
            String reversedWord = new StringBuilder(eachWord).reverse().toString();
            secondReverse.append(reversedWord);
            secondReverse.append(" ");

        }

        System.out.println("Old String:"+string);   //Prints out I love you
        System.out.println("New String : "+reverse);//Prints out the reverse  that is "uoy evol I"
        System.out.println("Reversed word two: " + secondReverse.toString());
    }
}

API: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM