JAVA中去掉空格經典整理
JAVA中去掉空格
1. String.trim() --------------trim()是去掉首尾空格
2.str.replace(" ", ""); 去掉所有空格,包括首尾、中間
String str = " hell o Wor d"; String str2 = str.replaceAll(" ", ""); System.out.println(str2);
3.或者replaceAll(" +",""); 去掉所有空格
4.str = .replaceAll("\\s*", "");
可以替換大部分空白字符, 不限於空格
\s 可以匹配空格、制表符、換頁符等空白字符的其中任意一個。
5.下面的代碼也可以去掉所有空格,包括首尾、中間
1 public String remove(String resource,char ch) 2 { 3 StringBuffer buffer=new StringBuffer(); 4 int position=0; 5 char currentChar; 6 7 while(position<resource.length()) 8 { 9 currentChar=resource.charAt(position++); 10 if(currentChar!=ch) buffer.append(currentChar); } return buffer.toString(); 11 } 12 -------------------------------Test----------------------------------------------------- 13 14 package practisedemo; 15 public class Demo{ 16 17 public static String remove(String resource,char ch) 18 { 19 StringBuffer buffer=new StringBuffer(); 20 int position=0; 21 char currentChar; 22 23 while(position<resource.length()) 24 { 25 currentChar=resource.charAt(position++); 26 //如果當前字符不是要去除的字符,則將當前字符加入到StringBuffer中 27 if(currentChar!=ch) buffer.append(currentChar); 28 } 29 return buffer.toString(); 30 } 31 public static void main(String args[]) { 32 String str= "afdsfdf 了 2012 0407 Alamps 老師"; 33 char c=' '; 34 System.out.println("結果為:"+Demo.remove(str, c)); 35 36 37 } 38 }
實例演示
有一個字符串開頭或結尾含有n個空格(” abcdefgdddd ”),欲去掉前后空格,返回一個新字符串。
1 int trimSpace(char *bufscr,char *bufdes) 2 { 3 int i=0; 4 char *p=bufscr;//指針變量,為了不修改傳入指針 5 int len=strlen(bufscr); 6 int j=len-1; 7 int count;//非空字符長度 8 int ret=0; 9 //首先判斷傳入的指針是否為空 10 if (bufscr==NULL||bufdes==NULL) 11 { 12 ret=-1; 13 printf("func trimSpace err %d:",ret); 14 return ret; 15 } 16 17 while(isspace(p[i])&&p[i]!='\0') 18 { 19 i++; 20 } 21 22 while(isspace(p[j])&&j>0) 23 { 24 j--; 25 } 26 count=j-i+1; 27 28 memcpy(bufdes,p+i,count); 29 //這里一定要注意,字符串數組和字符串的區別就在於字符串數組末尾多'\0'。 30 bufdes[count]='\0'; 31 return ret; 32 }
打印結果如下所示