/**
-
去除 字符串空格
*/
public class TrimBlank {public static void main(String[] args) {
String str = " acd xx oij ";// trim 只能去掉 字符串 两端空格 String new_str = str.trim(); System.out.println(new_str); /** * 方法一 * str.replace(" ", ""); 去掉所有空格,包括首尾、中间 */ String str2 = str.replace(" ", ""); System.out.println(str2); /** * 方法二 * str.replaceAll(" ", ""); 去掉所有空格,包括首尾、中间 */ String str3 = str.replaceAll(" ", ""); System.out.println(str3); /** * 方法三 : 正则表达式 * str.replaceAll("\\s*", ""); * 可以替换大部分空白字符, 不限于空格 * \s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 */
String str4 = str.replaceAll("\s*", “”);
System.out.println(str4);
/**
* 方法四: 生成新的字符串
* 不使用 replace 方法
*/
String str5 = replaceSpace(str);
System.out.println(str5);
}
public static String replaceSpace(String s){ if(null == s){ return s; } String result = ""; for (int i=0 ; i<s.length(); i++){ if (s.charAt(i)==' '){ continue; }else{ result+= s.charAt(i); } } return result; }
}