for 循环字符串长度奇怪地跳过一些字符

421*_*212 2 java string for-loop char

正如标题中提到的,我在从文件中读取的字符串上运行 for 循环,试图删除每个-字符,但奇怪的是删除了一些并跳过了其他。这是正在处理的字符串: 在此处输入图片说明

这是我的功能:

        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);
Run Code Online (Sandbox Code Playgroud)

输出 :

在此处输入图片说明

Bub*_*ter 5

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

newSeq = newSeq.replace("-", "");
Run Code Online (Sandbox Code Playgroud)