Java指定String方法实现字符全移除程序仅删除部分实例问题
问题分析与修复方案
你的程序只能部分移除目标字符,核心问题有两个:
问题1:循环条件漏掉最后一个字符
你写的i < userString.length() - 1会让循环提前结束,最后一个字符根本没被检查,自然没法删除。
问题2:删除字符后索引跳过相邻目标字符
当你删除索引i的字符后,原字符串中i+1位置的字符会前移到i位置,但循环的i会继续自增,导致这个前移过来的目标字符被跳过。比如原字符串是"goooo",删除索引1的'o'后,字符串变成"gooo",此时索引1还是'o',但i会变成2,直接跳过了这个字符。
修复方案1:调整循环逻辑,删除后不递增索引
把循环条件改成i < userString.length(),并且在删除字符时不执行i++(因为后续字符前移了,当前i位置需要重新检查)。修改后的代码如下:
import java.util.Scanner; public class LabTester { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String userString = "goooo dawwwwgs"; String charToRemove = ""; System.out.println("Enter the character to remove"); charToRemove = sc.nextLine(); int i = 0; while (i < userString.length()) { if (userString.substring(i, i+1).equals(charToRemove)) { userString = userString.substring(0, i) + userString.substring(i + 1); // 删除后不递增i,当前位置是原i+1的字符,需要重新检查 } else { i++; } } System.out.println("The new sentence is: " + userString); } }
修复方案2:创建新字符串拼接(更稳妥)
这种方法不会有索引混乱的问题,遍历原字符串,把不需要删除的字符拼接到新字符串里,完全符合允许使用的方法:
import java.util.Scanner; public class LabTester { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String userString = "goooo dawwwwgs"; String charToRemove = ""; System.out.println("Enter the character to remove"); charToRemove = sc.nextLine(); String result = ""; for (int i = 0; i < userString.length(); i++) { String currentChar = userString.substring(i, i+1); if (!currentChar.equals(charToRemove)) { result += currentChar; } } System.out.println("The new sentence is: " + result); } }
两种方案都能彻底删除所有目标字符实例,第二种逻辑更清晰,不容易出错。
内容的提问来源于stack exchange,提问作者JavaStudent513
相关产品推荐
相关产品推荐

