去除字符串中的char(比如空格)

因为要去除一个字符串中的所有空格,没有找到现成可用的方法,所以写了一下.

比较下来,removeChar和removeChar2的执行效率时间为 5:8.  可能是因为removeChar2中,创建了更多的对象的缘故?

package all;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateTest {
    /**
     * Logger for this class
     */
    private static final Log logger = LogFactory.getLog(DateTest.class);

    public static void main(String[] args) {      
        String text="  a bc  d efghijkl   mn opq      rst uvwxyz  ";
       
        logger.info(removeChar(text, ' '));
       
        long begin=System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            removeChar(text, ' ');
        }
        logger.info(System.currentTimeMillis()-begin);
       
        begin=System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            removeChar2(text, ' ');
        }
        logger.info(System.currentTimeMillis()-begin);
    }
   
    public static String removeChar(String str,char c){
        char[] array=str.toCharArray();
       
        int lastIndex=0;
        int length=array.length;
       
        for (int i = 0; i < length; i++) {
            char value=array[i];
            if(value!=c){
                if(lastIndex<i){
                    array[lastIndex]=value;
                    array[i]=c;
                }
               
                lastIndex++;
            }
        }
       
        return new String(array,0,lastIndex);
    }
   
    public static String removeChar2(String str,char c){
        StringBuilder builder=new StringBuilder();
        char[] array=str.toCharArray();
        for (int i = 0; i < array.length; i++) {
            char value=array[i];
            if(value!=c){
                builder.append(c);
            }
        }
        return builder.toString();
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值