英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论