str.replace(" ","")的问题

bibleboy 2004-05-06 04:22:09
我想实现的功能是:去除一个String中的空格
但是replace方法的第2个参数不能为空串,标题中的写法不成立。
有没有简单的方法来实现,
不要告诉我只能用1个个判,然后字符串连接
...全文
74 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
bibleboy 2004-05-06
  • 打赏
  • 举报
回复
maowu(猫呜)说的对,是我搞错了,
因为我一开始用的是replace(' ','')第2个参数不能为空串
str.replace(" ","")是可以编译通过的,谢谢大家。
jiabiao011 2004-05-06
  • 打赏
  • 举报
回复
把你的replace改成replaceall就行了!
maowu 2004-05-06
  • 打赏
  • 举报
回复
String str = "123 456";
System.out.println(str.replaceAll(" ", ""));

输出的结果是123456,没有问题啊.
jiabiao011 2004-05-06
  • 打赏
  • 举报
回复
public class StringTest {
public StringTest() {
String str=new String("234 789");
String newStr=str.replaceAll(" ","2");
System.out.println(newStr);
}
public static void main(String[] args) {
StringTest stringTest1 = new StringTest();
}

}
不知道是不是你想要的结果!
Arias 2004-05-06
  • 打赏
  • 举报
回复
如果只是简单的去掉前后的空格的话,那么用string的trim()方法就可以那!

但是要想去掉字符窜中间的空格的话,好像是没有直接的方法的!只能找或者自己写替代的方法!

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧