在Java中,可以使用以下方法去除字符串中的空格:
- 使用
trim()
方法去除字符串两端的空格:
String str = " hello world ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 输出: "hello world"
- 使用
replaceAll()
方法去除字符串中所有空格:
String str = " hello world ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
- 使用
replace()
方法去除字符串中所有空格:
String str = " hello world ";
String noSpaceStr = str.replace(" ", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
这些方法可以根据具体需求选择使用哪种去除空格的方式。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/930294.html