Java去除字串中空格的方法詳解
阿新 • • 發佈:2020-07-19
1、方法
- str.trim(); //去掉首尾空格
- str.replace(" ",""); //去除所有空格,包括首尾、中間
- str.replaceAll(" ", ""); //去掉所有空格,包括首尾、中間
- str.replaceAll(" +",""); //去掉所有空格,包括首尾、中間
- str.replaceAll("\\s*", ""); //可以替換大部分空白字元, 不限於空格 ;
\\s* 可以匹配空格、製表符、換頁符等空白字元的其中任意一個。
2、示例
package test; public class Test { /** * description:字串去除空格的方法 */ public static void main(String[] args) { String str = " hi world ~ "; //方法1:str.trim() System.out.println("1--->"+str.trim()); //方法2:str.repalce(" ","") System.out.println("2--->"+str.replace(" ", "")); //方法3:str.repalceAll(" ","") System.out.println("3--->"+str.replaceAll(" ", "")); //方法4:str.repalceAll(" +","") System.out.println("4--->"+str.replaceAll(" +", "")); //方法5:str.repalceAll("\\s*","") System.out.println("4--->"+str.replaceAll("\\s*", "")); } }
3、replace和replaceAll是JAVA中常用的替換字元的方法,它們的區別是:
(1) replace 的引數是char和CharSequence,即可以支援字元的替換,也支援字串的替換
(2) replaceAll 的引數是 regex ,即基於正則表示式的替換,比如,可以通過replaceAll("\\d", "*")把一個字串所有的數字字元都換成星號;
相同點:都是全部替換,即把源字串中的某一字元或字串全部換成指定的字元或字串,如果只想替換第一次出現的,可以使用
replaceFirst(),這個方法也是基於規則表示式的替換,但與replaceAll()不同的時,只替換第一次出現的字串
REF
https://www.jb51.net/article/168793.htm