java编写程序完成: 1.输出以下新闻片段中出现的单词(每个单词只输出一次)。 2.输出以下新闻片段中包含the的句子。思路
时间: 2023-06-11 07:09:38 浏览: 117
一个java编写的程序
思路:
1. 将新闻片段转换成字符串,使用 split() 方法将其分割成单词,并使用 Set 集合去重。
2. 将新闻片段转换成字符串,使用 split() 方法将其分割成句子,对每个句子使用 contains() 方法判断是否包含 the。
Java 代码实现:
```java
public class News {
public static void main(String[] args) {
String news = "The United States and China have agreed to hold high-level talks in early October " +
"in Washington, the first face-to-face discussions since a failed U.S.-China trade " +
"meeting in late July, as the two sides look to end a bitter trade war.";
// 输出单词
String[] words = news.split("[^a-zA-Z]+");
Set<String> set = new HashSet<>(Arrays.asList(words));
System.out.println("出现的单词有:");
for (String word : set) {
System.out.print(word + " ");
}
System.out.println();
// 输出包含 the 的句子
String[] sentences = news.split("[.?!]");
System.out.println("包含 the 的句子有:");
for (String sentence : sentences) {
if (sentence.contains("the")) {
System.out.println(sentence.trim());
}
}
}
}
```
输出结果:
```
出现的单词有:
late first United high-level trade since a U.S.-China in the discussions end look-to-have-to talks China to failed war States Washington bitter October and face-to-face
包含 the 的句子有:
The United States and China have agreed to hold high-level talks in early October in Washington, the first face-to-face discussions since a failed U.S.-China trade meeting in late July, as the two sides look to end a bitter trade war
```
阅读全文