我试图消除所有出现的' X'在字符串"清理"但我一直得到一个异常的例外。我的代码出了什么问题? 我需要使用while循环和int loc来消除发生
public static void main (String [] args)
{
String cleaned = "abcXabcXabc";
char remove= 'X';
int loc = cleaned.indexOf(remove);
System.out.println ("before: "+ cleaned);
while (loc != -1)
{
String part1= cleaned.substring(0, loc);
String part2= cleaned.substring(loc+1);
cleaned = part1+part2;
}
System.out.println ("after: " + cleaned);
}
答案 0 :(得分:1)
问题在于您永远不会更新loc
。
public static void main(String[] args)
{
String cleaned = "abcXabcXabc";
char remove = 'X';
int loc;
while ((loc = cleaned.indexOf(remove)) != 1)
{
String part1 = cleaned.substring(0, loc);
String part2 = cleaned.substring(loc + 1);
cleaned = part1 + part2;
}
System.out.println("after: " + cleaned);
}
while
语句中使用的表达式可能会让您感到困惑,我会尝试解释它:
int loc;
。X
分配的新索引。loc
,然后检查为-1
。当然,如果您真的愿意在实际应用程序中编写类似的内容,那么您可能希望使用String.replace(target, replacement)
这样的内容:
public static void main(String[] args)
{
String cleaned = "abcXabcXabc";
// Notice this is now a String
String remove = "X";
cleaned = cleaned.replace(remove, "");
System.out.println("after: " + cleaned);
}
答案 1 :(得分:0)
public static void main (String [] args)
{
String cleaned = "abcXabcXabc";
char remove= 'X';
int loc = cleaned.indexOf(remove);
int currentPos = 0;
String result = "";
System.out.println ("before: "+ cleaned);
while (loc != -1)
{
result = result + cleaned.substring(currentPos,loc);
currentPos = loc+1;
loc = cleaned.indexOf(remove, currentPos);
}
System.out.println ("after: " + result);
}
这应该可以胜任。您可能希望查看StringBuilder类。