java 字符串唯一数字
时间: 2023-06-28 12:12:46 浏览: 56
如果你想在一个字符串中找到唯一的数字,可以使用正则表达式和Set数据结构来实现。以下是一个Java代码示例:
```java
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UniqueNumbersInString {
public static void main(String[] args) {
String str = "ab1c2d3e4f5g6h7i8j9k0";
Set<Integer> uniqueNumbers = new HashSet<>();
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
int num = Integer.parseInt(matcher.group());
if (!uniqueNumbers.contains(num)) {
uniqueNumbers.add(num);
}
}
System.out.println("Unique numbers in the string: " + uniqueNumbers);
}
}
```
运行结果为:
```
Unique numbers in the string: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
这个程序使用了正则表达式 `\d+` 来匹配字符串中的数字,并将其转换为整数。然后使用Set数据结构来保存唯一的数字。
相关推荐
![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)