Java程序以反转字符串中的单词

huangapple go评论80阅读模式
英文:

Java program to reverse words in a string

问题

我只想要输出中每个单词之间只有一个空格,不管输入中的单词之间有多少个空格。但在下面的代码中,输出中"love"和"java"之间的空格与输入中的空格相同。

public class Main {
    public static void main(String[] args) {
        String s = "I love       java programming.";

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

输出:

programming. java       love I
英文:

I want only one space in output between every word no matter how much spaces between the words in input. But in following code spaces in output between love and java same as input spaces.

public class Main {
	public static void main(String[] args) {
		String s = "I love       java programming.";

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

Output:--

programming. java       love I 

答案1

得分: 2

我完全同意@Johannes Kuhn。

问题是,你传递给方法split的过滤器只能检测单个空格。

这可以通过传递正确的正则表达式来轻松解决,以便检测多个空格和句子末尾的句号

请查看以下实现:

public class Main {

    public static void main(String[] args) {
        String s = "我爱       Java 编程。";

        String ss[] = s.split("[\\.| ]+");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

附注: 如果句号对你不重要,你可以使用[ ]+

英文:

I completely agree with @Johannes Kuhn.

The problem is, the filter you passed to the method split detects only single spaces.

This can be solved easily by passing correct regex expression to detect multiple spaces and dots and the end of the sentence.

Have a look at the following implementation:

public class Main {

    public static void main(String[] args) {
        String s = "I love       java programming.";

        String ss[] = s.split("[\\.| ]+");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

PS: You can use "[ ]+" if dots doesn't matter to you.

答案2

得分: 0

以下是代码的翻译部分:

import java.util.Arrays;

class Main {

  public static void main(String ... args) {

    var s = "I love     java programming";
    var r = new StringBuilder();
    var parts = s.split("\\s +");
    Arrays.asList(parts).forEach(r::append);
    System.out.println(r.reverse().toString());

  }
}

输出: gnimmargorp avajevol I

英文:

Small variation using StringBuilder and Lambdas

import java.util.Arrays;

class Main {

  public static void main(String ... args) {

    var s = "I love     java programming";
    var r = new StringBuilder();
    var parts = s.split("\\s +");
    Arrays.asList(parts).forEach(r::append);
    System.out.println(r.reverse().toString());

  }
}

Output: gnimmargorp avajevol I

Repl

huangapple
  • 本文由 发表于 2020年4月7日 21:59:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61081758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定