java去掉字符串中空格怎么操作

Java中,我们可以使用多种方法来去除字符串中的空格,以下是一些常用的方法:

java去掉字符串中空格怎么操作
(图片来源网络,侵删)

1、使用 replaceAll() 方法:此方法是使用正则表达式替换字符串中的所有空格。

2、使用 trim() 方法:此方法仅删除字符串开头和结尾的空格。

3、使用 replace() 方法:此方法用于替换字符串中的所有空格。

4、使用 split() 方法:此方法将字符串按照空格分割成多个子字符串,然后我们可以将这些子字符串重新组合成一个没有空格的新字符串。

5、使用 stream() 方法和 Collectors.joining() 方法:此方法将字符串转换为字符流,然后删除所有的空格,最后再将字符流重新组合成一个字符串。

以下是这些方法的具体代码示例:

1、使用 replaceAll() 方法:

String str = "Hello World";
str = str.replaceAll("\s", "");
System.out.println(str);  // 输出 "HelloWorld"

2、使用 trim() 方法:

String str = " Hello World ";
str = str.trim();
System.out.println(str);  // 输出 "Hello World"

3、使用 replace() 方法:

String str = "Hello World";
str = str.replace(" ", "");
System.out.println(str);  // 输出 "HelloWorld"

4、使用 split() 方法:

String str = "Hello World";
str = String.join("", str.split(" "));
System.out.println(str);  // 输出 "HelloWorld"

5、使用 stream() 方法和 Collectors.joining() 方法:

String str = "Hello World";
str = str.chars().filter(c > c != ' ').mapToObj(c > (char) c).collect(Collectors.joining());
System.out.println(str);  // 输出 "HelloWorld"

以上就是在Java中去除字符串中空格的一些常用方法,你可以根据你的具体需求选择最适合你的方法。

原创文章,作者:酷盾叔,如若转载,请注明出处:https://www.kdun.com/ask/300422.html

(0)
酷盾叔订阅
上一篇 2024-03-03 14:33
下一篇 2024-03-03 14:34

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入