将多个空格替换为一个:
string=string.replaceAll(" +"," ");
简单又好用!
必须是replaceAll方法,replace不可以!
/**
* Created by tiantao on 14-11-27.
*/
public class Test {
public static void main(String[] args){
String s = " ";
System.out.println("a" + s.replaceAll(" +"," ") + "b");
System.out.println("a" + s.replace(" +"," ") + "b");
}
}
本文介绍了一个简单的Java程序,演示如何使用replaceAll方法来处理字符串中的连续空格问题。通过实例对比了replaceAll与replace方法的不同之处,强调了在进行字符串操作时选择合适方法的重要性。
6851

被折叠的 条评论
为什么被折叠?



