1

我有一个字符串,类似于 9.555.555,00 并且想要删除所有符号并只保留数字,这是字符串格式。

我使用 indexof 来查找特殊字符,然后使用循环以在循环到达特定字符时跳过特定字符,因此它不会将该字符附加到最终字符串。

但是,在执行此操作时,代码似乎选择了第一次出现的句点符号,但 indexOf() 第二次返回 -1,即使还有另一个 . 在字符串中。

int dotIndex, commaIndex;

        dotIndex = tempBalance.indexOf('.');
        commaIndex = tempBalance.indexOf(',');

        for(int j = 0; j < tempBalance.length(); ++j){

            //System.out.println("Iteration: " + j + " ~ i @ : " + i);

            if(j == dotIndex){
                System.out.println("Current dot Index: " + dotIndex + " J: " + j + " : " + tempBalance);
                dotIndex = tempBalance.indexOf(j+1, '.');
                System.out.println("New dotIndex: " + dotIndex);
                continue;
            } else if(j == commaIndex){
                break;
            } else {

                tempString.append(tempBalance.charAt(j));
                //System.out.print("Found normal Number: " + tempBalance.substring(j, (j+1)));
            }

system.out.println 的输出:

当前点索引:1 J:1:9.955.458,23
新点索引:-1

4

5 回答 5

3
dotIndex = tempBalance.indexOf(j+1, '.');

应该改为

dotIndex = tempBalance.indexOf('.', j+1);

但这不是唯一的问题。一旦你有'.'固定的。你仍然需要整理所有的解析','。简单地修复上述问题仍然只会返回9955458减去23

于 2013-07-22T10:11:42.200 回答
2

tempBalance.indexOf(j+1, '.')应该是tempBalance.indexOf('.', j+1)。有关. _indexOf(int, int)

于 2013-07-22T10:10:09.917 回答
2

您应该在以下位置切换参数位置indexOf

dotIndex = tempBalance.indexOf('.', j + 1);

第一个参数是要搜索的字符,第二个是要开始的索引。

于 2013-07-22T10:10:35.367 回答
1

要删除非数字字符,您可以执行 -

public static String removeNonDigits(String input) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (Character.isDigit(c)) {
            result.append(c);
        }
    }
    return result.toString();
}

此外,对于格式化数字,您可以将NumberFormat与 Locale 一起使用。

于 2013-07-22T10:10:35.720 回答
0
want to remove all the symbols(.,) and just keep the numbers

使用正则表达式:

String exprStr="9.555.555,00";
exprStr=exprStr.replaceAll("[.,]","");
System.out.println(exprStr);

其中[.,]是标识其中一个的正则表达式,

于 2013-07-22T10:19:27.963 回答