【问题标题】:Reversing the whole String and reversing each word in it反转整个字符串并反转其中的每个单词
【发布时间】:2015-02-13 22:39:25
【问题描述】:

我必须编写一个包含两个类的代码,一个反转一个字符串改变位置,例如

I love you 变为 uoy evol I

另一个类在不改变位置的情况下反转字符串,例如

I love you 变为 I evol uoy

我有一个小代码,但如果调用这些类中的方法,我无法找到方法。

我现在所拥有的只是以第一种方式反转字符串的代码。欢迎任何帮助。

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"
    }
}

【问题讨论】:

  • 只是一个建议,避免使用Reserved Keywords 作为变量/对象名称。有时可能会导致意外行为。
  • @Prera​​kSola: 比如?
  • 我当然希望它不会“有时”导致“意外”行为;而不是它导致预期编译器错误总是
  • @njzk2 - 如String string
  • @njzk2 - @PrekSola 所说的是避免 String stringArrayList arrayList。它使阅读更容易。当然string all lower case 不是保留字,但它只是所有小写的保留字。查看this post about class vs clazz。这是一个很好的约定

标签: java methods


【解决方案1】:

我不会向您展示完整的解决方案,但会指导您,这是一种方法:

  • split 根据空格的字符串 (yourString.split("\\s+");)
  • 在结果数组上迭代并反转每个字符串(您可以使用与第一个任务相同的方法)
  • 从数组中构造一个新字符串

还有更多解决方案,请访问String API 并点燃您的创意之火!

【讨论】:

  • 你为什么选择split("\\s+") 而不是split(" ")
  • @Ascalonian 因为它更通用," " 是一个匹配单个空格的正则表达式,\\s+ 匹配一个 或多个 个空格,所以它可以用于字符串比如"abc____def_g_____hi jk"_ 是一个空格)
【解决方案2】:

你可以在 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

【讨论】:

  • 我没有投反对票,但又看了一遍问题,你没有回答。
  • 基本上,您在答案中的代码是他在他的问题中工作的唯一部分。您没有足够仔细地阅读问题。
  • 感谢 - 已更改以反映问题
  • 现在它是正确的,+1,但下次尽量不要为没有表现出最小努力的问题提供完整的解决方案。
  • @MarounMaroun 他有他写的代码,我称之为显示“最小的努力”。虽然,这个问题的答案很可能在网络上找到......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2017-06-15
  • 2021-04-28
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多