java字符串去除重复的单词
时间: 2023-09-07 16:05:08 浏览: 76
要去除Java字符串中重复的单词,我们可以使用正则表达式和字符串方法来实现。
首先,我们可以使用split方法将字符串分割成一个个单词,并存储在一个字符串数组中。
接下来,我们可以使用HashSet来存储不重复的单词。HashSet是一种无序的集合,可以自动去除重复的元素。
然后,我们可以遍历字符串数组,将每个单词加入HashSet中。由于HashSet会自动去重,所以最终的HashSet中只保留了不重复的单词。
最后,我们可以使用StringBuilder来构建去除重复单词后的字符串。我们可以遍历HashSet中的单词,将它们加入到StringBuilder中,并在单词之间添加空格。
下面是一个示例代码:
```java
import java.util.HashSet;
public class RemoveDuplicateWords {
public static String removeDuplicateWords(String input) {
String[] words = input.split(" ");
HashSet<String> uniqueWords = new HashSet<>();
for (String word : words) {
uniqueWords.add(word);
}
StringBuilder result = new StringBuilder();
for (String word : uniqueWords) {
result.append(word).append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
String input = "java is a programming language java is widely used";
String output = removeDuplicateWords(input);
System.out.println(output); // 输出: java is a programming language widely used
}
}
```
在上面的示例代码中,我们先将输入字符串按空格分割成单词数组,然后遍历单词数组将单词添加到HashSet中。最后,将HashSet中的单词按顺序添加到StringBuilder中,并返回去除重复单词后的字符串。
希望这个解答对您有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)