简体   繁体   English

反转整个字符串并反转其中的每个单词

[英]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 I love you成为uoy evol I

and the other class reverses the string without changing positions eg 而另一类在不改变位置的情况下反转字符串,例如

I love you becomes I evol uoy . I love you变成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+"); ) 根据空格split String( yourString.split("\\\\s+");
  • iterate on the resulted array and reverse each String (you can use the same method you use for your first task) 迭代结果数组并反转每个String(您可以使用与第一个任务相同的方法)
  • construct a new String from the array 从数组构造一个新的String

There are many more solutions, visit the String API and fuel your creative fire! 还有更多解决方案,请访问String API并激发您的创造力!

you can just use the reverse() method on a StringBuilder object 您可以在StringBuilder对象上使用reverse()方法

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 API: http : //docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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