专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java去除空格的方法

Java去除空格的方法

更新时间:2022-12-19 11:43:05 来源:星辉 浏览5381次

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.下面的代码也可以去掉所有空格,包括首尾、中间

 public String remove(String resource,char ch)   
     {   
         StringBuffer buffer=new StringBuffer();   
         int position=0;   
         char currentChar;      
         while(position<resource.length())   
         {   
             currentChar=resource.charAt(position++);   
             if(currentChar!=ch) buffer.append(currentChar); } return buffer.toString();   
     }  
 -------------------------------Test-----------------------------------------------------  
 package practisedemo;
 public class Demo{  
  public static String remove(String resource,char ch)   
  {   
      StringBuffer buffer=new StringBuffer();   
      int position=0;   
      char currentChar;    
      while(position<resource.length())   
      {   
          currentChar=resource.charAt(position++);  
          //如果当前字符不是要去除的字符,则将当前字符加入到StringBuffer中
          if(currentChar!=ch) buffer.append(currentChar); 
      } 
      return buffer.toString();   
  }
  public static void main(String args[]) {
    String str= "afdsfdf 了   2012   0407 Alamps 老师";
    char c=' ';
       System.out.println("结果为:"+Demo.remove(str, c));              
  }
 }

实例演示

有一个字符串开头或结尾含有n个空格(” abcdefgdddd ”),欲去掉前后空格,返回一个新字符串。

 int trimSpace(char *bufscr,char *bufdes)
 {
     int i=0;
     char *p=bufscr;//指针变量,为了不修改传入指针
     int len=strlen(bufscr);
     int j=len-1;
     int count;//非空字符长度
     int ret=0;
     //首先判断传入的指针是否为空
     if (bufscr==NULL||bufdes==NULL)
     {
         ret=-1;
         printf("func trimSpace err %d:",ret);
         return ret;
     }  
     while(isspace(p[i])&&p[i]!='')
     {
         i++;
     }  
     while(isspace(p[j])&&j>0)
     {
         j--;
     }
     count=j-i+1;  
     memcpy(bufdes,p+i,count);
     //这里一定要注意,字符串数组和字符串的区别就在于字符串数组末尾多''。
     bufdes[count]='';
     return ret;
 }

打印结果如下所示

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>