Java中去除字串中空格的幾種方法
阿新 • • 發佈:2019-01-10
1.直接上程式碼
package com.examplezhc.demo; import android.os.Bundle; import android.app.Activity; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String str = " Hello Word! "; //方法1:String.trim();trim()是去掉首尾空格 System.out.println("1:"+str.trim()); //方法2:str.replaceAll(" ", ""); 去掉所有空格,包括首尾、中間 String str2 = str.replaceAll(" ", ""); System.out.println("2:"+str2); //方法3:或者replaceAll(" +",""); 去掉所有空格,包括首尾、中間 String str3 = str.replaceAll(" +", ""); System.out.println("3:"+str3); //方法4:、str = .replaceAll("\\s*", "");可以替換大部分空白字元, 不限於空格 ; \s 可以匹配空格、製表符、換頁符等空白字元的其中任意一個。 String str4 = str.replaceAll("\\s*", ""); System.out.println("4:"+str4); } }
2.列印結果:
10-11 11:59:43.195: I/System.out(4449): 1:Hello Word!
10-11 11:59:43.195: I/System.out(4449): 2:HelloWord!
10-11 11:59:43.195: I/System.out(4449): 3:HelloWord!
10-11 11:59:43.205: I/System.out(4449): 4:HelloWord!
3.參考博文:
http://zhidao.baidu.com/link?url=99-shJbqbq7t37p0CDe4t62uoy882z2aXm_87TECuc4ivtPe-uGwiifrMYd9fA4uwYrMg565pD8aerwJ7X8PR_
http://blog.csdn.net/hmyang314/article/details/37883563