Java中把字符串内非数字字符删掉
时间: 2023-09-21 17:02:35 浏览: 43
可以使用正则表达式来删除字符串中的非数字字符,示例代码如下:
```java
String str = "a1b2c3";
str = str.replaceAll("\\D+", "");
System.out.println(str); // 输出 123
```
其中,`\\D+` 表示匹配所有非数字字符,`replaceAll()` 方法用于将匹配到的字符替换为空字符串。
相关问题
java中删除字符串中的元素
在Java中,字符串是不可变的,因此无法直接删除字符串中的元素。但是,可以通过创建新的字符串来删除特定的字符或子字符串。以下是一些常用的方法:
1.使用replace()方法来替换要删除的字符或子字符串:
```java
String str = "Hello World!";
str = str.replace("l", ""); //删除所有的'l'
System.out.println(str); //输出"Heo Word!"
```
2.使用substring()方法来截取要保留的部分:
```java
String str = "Hello World!";
str = str.substring(0, 4) + str.substring(6); //删除第5个字符'l'
System.out.println(str); //输出"Helo World!"
```
3.使用StringBuilder或StringBuffer类来构造新的字符串:
```java
String str = "Hello World!";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(4); //删除第5个字符'l'
str = sb.toString();
System.out.println(str); //输出"Helo World!"
```
java字符串删除字符串_Java从字符串中删除字符
在 Java 中,我们可以使用 String 类的 replace() 或者replaceAll() 方法来删除字符串中的指定字符。
例如,我们想要删除字符串 "hello world" 中的所有空格,可以使用以下代码:
```java
String str = "hello world";
str = str.replace(" ", ""); // 使用 replace() 方法删除空格
System.out.println(str); // 输出 "helloworld"
```
如果我们想要删除字符串中的多个字符,可以使用 replaceAll() 方法,该方法支持正则表达式。
例如,我们想要删除字符串 "hello, world!" 中的逗号和感叹号,可以使用以下代码:
```java
String str = "hello, world!";
str = str.replaceAll("[,!]", ""); // 使用 replaceAll() 方法删除逗号和感叹号
System.out.println(str); // 输出 "hello world"
```
在上面的代码中,我们使用了正则表达式 "[,!]" 来匹配逗号和感叹号,然后将其替换为空字符串。
相关推荐
![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_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)
![](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)