字符串去掉末尾0

public static String getStr(String str) {
if (str == null) return str;
StringBuffer tempStr = new StringBuffer();
char[] chars = str.toCharArray();
boolean isLast = true;
for (int i = chars.length - 1; i >= 0; i--) {
if (isLast) {
if (chars[i] != '0') {
tempStr.append(chars[i]);
}
if (tempStr.length() > 0) {
isLast = false;
}
} else {
tempStr.append(chars[i]);
}
}
return tempStr.reverse().toString();
}

思路就是:从末尾开始数数,遇到不是0的字符,记录进入新的字符串,当新字符串有值的时候,遇到0就不是末尾的0,就要加入新的字符串,最后新字符串翻转即可得到正确的值。
posted @ 2020-05-06 16:33  参禅悟道  阅读(2806)  评论(0)    收藏  举报