使用indexOf()两次无法检测第二个字符的出现

时间:2013-07-22 10:00:00

标签: java string loops

我有一个字符串,类似于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
  新dotIndex:-1

5 个答案:

答案 0 :(得分:3)

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

应该是

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

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

答案 1 :(得分:2)

tempBalance.indexOf(j+1, '.')应为tempBalance.indexOf('.', j+1)。 请参阅Javadocs for indexOf(int, int)

答案 2 :(得分:2)

您应该在indexOf中切换参数位置:

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

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

答案 3 :(得分: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与区域设置一起使用。

答案 4 :(得分: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);

[。,] 是标识

的正则表达式
相关问题