两种方法 去除字符串中空格制表符换行:
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;
}
去除数组中的null
/**
* 清空数组中的null
*
* @param array 元素组
* @param <T> 数组元素类型
* @return 去除null之后的新数组
*/
public static <T> T[] clearEmptyElements(T[] array) {
if (array == null || array.length == 0) {
return null;
}
int m = 0, n = 0;
while (m < array.length) {
T t = array[m];
if (t != null) {
if (m != n) {
array[n] = t;
}
n++;
}
m++;
}
return Arrays.copyOf(array, n);
}
}
补充两种去除的算法
//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];
}