Android去除字符串中空格制表符换行

来源:互联网 发布:java面试问题 编辑:程序博客网 时间:2024/05/01 13:36

两种方法 去除字符串中空格制表符换行:

  public String checkString(String str) {        if (TextUtils.isEmpty(str)) return "";        int len = str.length();        int i = 0, j = 0;        char[] strChar = str.toCharArray();        for (; i < len; i++) {            if (' ' == strChar[i] || '\t' == strChar[i] || '\n' == strChar[i])                continue;            if (i != j) strChar[j] = strChar[i];            j++;        }        //strChar[j] = 0;//C/C++中0是结束标志位需要添加该语句,Java中会越界,需要注释该句;        return new String(Arrays.copyOf(strChar, j));    }

利用正则表达式

public static String replaceBlank(String src) {        String dest = "";        if (src != null) {            Pattern pattern = Pattern.compile("\t|\r|\n|\\s*");            Matcher matcher = pattern.matcher(src);            dest = matcher.replaceAll("");        }        return dest;    }

补充两种去除的算法

//2.1 Delete    int k = 0;    int i = 0;    while (i < NowListSize)    {        if (NowListFlag[i] == 0)        {            NowList[i]->deleteIcon();        }        else        {            NowList[k++] = NowList[i];        }        i++;    }    NowListSize = k;

或者

    int pos = 0;    for (int j = 0; j < NowListSize; j++)    {        if (NowListFlag[j + pos] == 0)        {            NowList[j + pos]->deleteIcon();            pos++;            NowListSize--;            j--;            continue;        }        NowList[j] = NowList[j + pos];    }
阅读全文
3 0
原创粉丝点击