我正在编写一个程序,它使用lambda表达式接受来自用户的字符串a,将其转换为全部小写并删除标点符号,然后按字母顺序列出唯一的单词 . 我无法让我的程序接受用户的句子并删除标点符号 . 我尝试过使用_20204但是我收到错误,所以我一定不能正确使用,或者说这不是正确的代码 . 任何帮助表示赞赏 . 这是我到目前为止的代码:
//I added my own string just to see if the code I have works.
public static void main(String[] args) {
String[] strings = {"The brown fox chased the white rabbit."};
System.out.printf("Original strings: %s%n", Arrays.asList(strings));
Stream<Map.Entry<String, Long>> uniqueWords = Arrays.stream(strings)
.map(String::toLowerCase)
//remove punctuation?
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.distinct();
System.out.println("Unique words in Alphabetical Order: "+ uniqueWords);
}
1 回答
您可以使用
Scanner
接受用户输入,使用nextLine()
方法接受来自控制台的一行输入 . 然后你可以toLowerCase()将句子转换为小写,然后split()来创建Array
. 您可以使用正则表达式\\W+
,它将拆分为任何非单词字符 .你也复杂了
Stream
. 您只需使用distinct()和sorted()按字母顺序创建唯一值流:Sample Input/Output: