gpt4 book ai didi

java - 对于字符串长度的循环奇怪地跳过一些字符

转载 作者:行者123 更新时间:2023-12-05 08:19:49 27 4
gpt4 key购买 nike

如标题中所述,我在从文件中读取的字符串上运行 for 循环,试图删除每个 - 字符,但它奇怪地删除了一些并跳过了其他字符。这是正在处理的字符串: enter image description here

这是我的功能:

        System.out.println(newSeq);
System.out.println(" String before deleteing - = " +newSeq + " length = " + newSeq.length());
for (int i = 0; i < newSeq.length(); i++) {
System.out.println("char at : " + i + " = " + newSeq.charAt(i) );
// Delete every -
if ( newSeq.charAt(i) == '-'){
StringBuilder lineString = new StringBuilder(newSeq);
lineString.deleteCharAt(i);
newSeq = lineString.toString();
}
}
System.out.println("String after deleting - = " + newSeq);

输出:

enter image description here

最佳答案

如果您不需要重新发明轮子,Java 已经有一个replace 方法:

newSeq = newSeq.replace("-", "");

关于java - 对于字符串长度的循环奇怪地跳过一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66920078/

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