使用replaceAll替换字符串中的一个或多个空格:
package think.in.java.test; /** * 测试replaceAll去除多个空格 * @author Administrator * */ public class Test_ReplaceAll { public static void main(String args[]) { //使用 replaceAll(" +"," ") 匹配一个或多个空格,然后替换成一个空格 String s1 = " SELECT ID,NAME, CODE FROM TABLE1 WHERE ID = '0101' "; s1 = s1.replaceAll(" +"," "); System.out.println("s1: "+ s1); //replace则不行 String s2 = " SELECT ID,NAME, CODE FROM TABLE1 WHERE ID = '0101' "; s2 = s2.replace(" +", " "); System.out.println("s2: " + s2); } }
执行结果:
s1: SELECT ID,NAME, CODE FROM TABLE1 WHERE ID = '0101'
s2: SELECT ID,NAME, CODE FROM TABLE1 WHERE ID = '0101'