I was working with StringBuilder to eliminate some unnecessary chars, I got some strange result.
String value = "1.045,00";
StringBuilder sanitized = new StringBuilder();
boolean decimalSeparatorFound = false;
char[] chars = value.toCharArray();
for (int i = chars.length-1; i >= 0; i--) {
if (chars[i] == ',' || chars[i] == '.') {
if (decimalSeparatorFound) continue; // skip this char
decimalSeparatorFound = true;
sanitized.append('.');
} else {
sanitized.append(chars[i]);
}
}
here I will get 00.5401 as a result in sanitized but when I was converting it to string like
String s = sanitized.reverse.toString();
and It is expected to print the value of s as 1045.00 but it get printed as 00.5401.
then I tried it as
StringBuilder sb = sanitized.reverse();
String s1 = sb.toString();
now this time it got printed correctly.
here my question why the StringBuilder is behaving this way? Isn't it performing reverse operation while assigning the value to String s?
for (int i = chars.length-1; i >= 0; i--) {sanitized.reverse().toString()should be identical withsb = sanitized.reverse(); s=sb.toString(). Did you miss something? Can you paste the 2 different codes?System.out.println(chars[i]);then replace the for loop with this:for (int i = 0; i < chars.length; i++) {to fix it