gpt4 book ai didi

java - 使用 indexOf() 两次未能检测到第二个字符的出现

转载 作者:行者123 更新时间:2023-11-29 10:16:04 27 4
gpt4 key购买 nike

我有一个字符串,例如 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 的输出:

Current dot Index: 1 J: 1 : 9.955.458,23
New dotIndex: -1

最佳答案

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

应该是

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

但这不是唯一的问题。修复了 '.' 之后。您还需要解决所有 ',' 的解析问题。简单地修复上面的问题仍然只会返回 9955458 减去 23

关于java - 使用 indexOf() 两次未能检测到第二个字符的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com