如何让程序在连字符后打印单词的反义词?

How to get program to print the reverse of a word AFTER a hyphen?

我已经完成了相反的部分,但我对连字符有疑问。任何帮助表示赞赏!另外,到目前为止的代码。

public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    System.out.print( "Enter a string of words that contains a hyphen: ");
    String word = kbd.next();
    for (int i = word.length()-1; i >= 0; i--) {            
          System.out.print(word.charAt(i));    
    }
}

示例输入:

low-budget

所需输出:

tegdub (the reverse of the part after the hyphen)

首先,根据-进行拆分。 然后,反过来看第二部分...

    String s = "low-budget";
    String[] t = s.split("-");
    for (int i = t[1].length() - 1; i >= 0; --i) {
        System.out.print(t[1].charAt(i));
    }

这是我能想到的最简单的解决方案(当然还有其他更好的解决方案,但这是我的实现:

public static void main(String[] args) {

    Scanner kbd = new Scanner(System.in);
    System.out.print( "Enter a string of words that contains a hyphen: ");
    String word = kbd.next();

    int loc = word.indexOf('-');    //Here I am trying to find the location of that hyphen

    for (int i = word.length()-1; i > loc; i--) { //Now print the rest of the String in reverse TILL that location where we found hyphen. Notic i > loc           
        System.out.print(word.charAt(i));    
    }

        System.out.print(" ");

    for (int i = loc + 1; i < word.length(); i++) { //Now print the original String starting after the hyphen. Notice int i = loc + 1
        System.out.print(word.charAt(i));    
    }
}

我会这样做(一行):

System.out.println(new StringBuilder(word.replaceAll(".*-", "")).reverse());

免费处理的边缘案例:

  • 如果没有连字符,则整个字符串被反转打印
  • 如果有多个连字符,则使用最后一个。要使用第一个,请将匹配正则表达式更改为 "^.*?-"
  • 如果字符串为空,则打印空白

想一想 不需要 编写的所有代码来处理这些(有效的)输入案例

分解其工作原理:

  1. word.replaceAll(".*-", "") 将所有匹配项替换为正则表达式 .*-,这意味着 "everything up to and including the (last) hyphen",使用空白 - 有效删除匹配项
  2. new StringBuilder(...) 创建一个 StringBuilder 并使用传递给构造函数的 String 进行初始化(从第 1 点开始)。我们需要 StringBuilder 的唯一原因是使用 reverse() 方法(String 没有)
  3. reverse() 反转 StringBuilder 的内容,returns 为下一次调用做好准备(参见 Fluent Interface
  4. 将非字符串传递给 System.out.println 会导致在对象上调用 String.valueOf(),这又会调用对象 toString() 方法,对于 StringBuilder returns 其内容

瞧!

这里有一个(单行)Java 8 个基于流的解决方案,供感兴趣:

word.chars().skip(word.indexOf('-') + 1).mapToObj(c -> String.valueOf((char)c))
  .reduce("", (a, b) -> b + a).ifPresent(System.out::println);

边缘案例处理:

  • 为了方便,如果没有连字符,整个 字符串将反向打印。这是由于indexOf(char)在未找到的情况下返回-1,所以最终结果是跳零(-1 + 1)
  • 如果存在多个连字符,则仅使用第一个连字符来拆分单词
  • 空白字符串不打印任何内容,因为 chars() 流是空的

要在输入为空白时打印空白,请改用此代码:

System.out.println(word.chars().skip(word.indexOf('-') + 1)
  .mapToObj(c -> String.valueOf((char)c)).reduce("", (a, b) -> b + a));

注意reduce()方法的替代形式的使用,其中传入空白("")的标识值,在空流的情况下使用保证还原效果。