Android去除字串中空格製表符換行
阿新 • • 發佈:2019-01-06
兩種方法 去除字串中空格製表符換行:
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];
}