
版权声明:本文为博主原创文章,未经博主允许不得转载。
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!