Thursday, June 6, 2013

Remove Trailing Zero in String

Remove Trailing Zero in String

Example 10000000 should be 1
and  1000001 should be 1000001

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
Test test = new Test();
System.out.println("" + test.removeTrailingZero("1000000001"));

}

public String removeTrailingZero(String inputValue) {
String inputOrignal = "";
if (inputValue != null) {

StringBuilder sb = new StringBuilder(inputValue);
String input = sb.reverse().toString();

int len = input.length();
int counter = 0;
char[] tempCharArray = new char[len];

// put original string in an array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] = input.charAt(i);
if (input.charAt(i) == '0') {
counter++;
} else {
break;
}
}
inputOrignal = inputValue.substring(0, (len - counter));
}
return inputOrignal;
}

}

No comments:

Post a Comment