Java 字符串
在Java中从字符串String中删除尾部零0
给定一串数字,从中删除尾随零。
例子:
输入:00000123569
输出:123569
输入:000012356090
输出:12356090
我们使用StringBuffer类,因为字符串是不可变的。
1)计算尾随零。
2)使用StringBuffer替换函数删除等于上述数量的字符。
// Java program to remove trailing/preceding zeros
// from a given string
import java.util.Arrays;
import java.util.List;
/* Name of the class to remove trailing/preceding zeros */
class RemoveZero
{
public static String removeZero(String str)
{
// Count trailing zeros
int i = 0;
while (str.charAt(i) == '0')
i++;
// Convert str into StringBuffer as Strings
// are immutable.
StringBuffer sb = new StringBuffer(str);
// The StringBuffer replace function removes
// i characters from given index (0 here)
sb.replace(0, i, "");
return sb.toString(); // return in String
}
// Driver code
public static void main (String[] args)
{
String str = "00000123569";
str = removeZero(str);
System.out.println(str);
}
}
输出:
123569