java 去除字符串中的空格
时间: 2023-09-04 18:16:27 浏览: 48
可以使用字符串的 `replaceAll()` 方法来去除空格,示例如下:
```java
String str = " hello world ";
str = str.replaceAll("\\s+", "");
System.out.println(str); // 输出"helloworld"
```
其中,`\\s+` 表示匹配一个或多个空格。如果想去除字符串两端的空格,可以使用 `trim()` 方法:
```java
String str = " hello world ";
str = str.trim();
System.out.println(str); // 输出"hello world"
```
相关问题
java中字符串去除空格
在Java中,可以使用字符串的`trim()`方法来去除字符串的空格。具体实现方法如下:
```java
String s = " hello world ";
s = s.trim(); // 去除字符串两端的空格
System.out.println(s); // 输出结果为"hello world"
```
另外,如果想去除字符串中间的空格,可以使用`replaceAll()`方法配合正则表达式来实现。具体实现方法如下:
```java
String s = " hello world ";
s = s.replaceAll("\\s+", ""); // 将一个或多个空格替换为空字符串
System.out.println(s); // 输出结果为"helloworld"
```
以上两种方法都可以有效地去除Java字符串中的空格。
java去除字符串中的空格
在Java中去掉字符串中的空格有多种方法。下面介绍一些常见的方法:
1. 使用replace()方法去除空格
String str = " Hello world! ";
String newStr = str.replace(" ", "");
System.out.println(newStr);
结果:Hello world!
2. 使用正则表达式去除空格
String str = " Hello world! ";
String newStr = str.replaceAll("\\s+", "");
System.out.println(newStr);
结果:Hello world!
3. 使用trim()方法去除首尾空格
String str = " Hello world! ";
String newStr = str.trim();
System.out.println(newStr);
结果:Hello world!
以上三种方法都可以去除字符串中的空格,具体使用哪种方法根据具体需求来选择。需要注意,第一种方法只能去除空格字符,如果字符串中还有其他空白字符如制表符等,就需要使用第二种或第三种方法。
相关推荐
![](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)