while 循环运行时到底发生了什么(while 循环内完成了什么)? (它应该删除子串和它后面的字符)

What exactly occurs when the while loop runs (what is done within the while loop)? (It's supposed to remove the substring and the character behind it)

 public String removeStrings()
 {  
    String cleaned = sentence; //sentence and remove are inputs
    int loc = cleaned.indexOf(remove);
    while (loc>-1) //need explanation on how this works
    { 
      cleaned = cleaned.substring(0, loc-1)+cleaned.substring(loc+remove.length());
      loc = cleaned.indexOf(remove);
    }
    return cleaned;
}

Example input sentence="xR-MxR-MHelloxR-M" and remove="R-M" //在这种情况下也必须删除 x https://github.com/AndrewWeiler/AndrewMac/blob/master/ACSWeiler/src/Lab09/StringRemover.java

String.substring() returns 两个位置之间的字符串部分(在 cleaned.substring(0, 1) 中,这将是位置 0 和 1 之间的 cleaned 的内容) 或者如果你只给那个方法 1 个 int 参数,它 returns 你的字符串的一部分,在那个位置之后。

例如,使用 sentence="xR-MxR-MHelloxR-M" and remove="R-M" 你会得到:

cleaned = "xR-MxR-MHelloxR-M"
loc = 1

所以 while 循环会像这样:

cleaned.substring(0, loc-1)returns"x"cleaned.substring(loc+remove.length())returns"xR-MHelloxR-M"。所以cleaned = "xxR-MHelloxR-M"。然后,loc 成为下一次出现 remove.

的位置

换句话说,您的 while 循环会从字符串 sentence 中删除字符串 remove 的每一次出现,并将结果保存在 cleaned.

对于 substring() 检查 https://www.javatpoint.com/substring.

编辑:

如果你也想删除子字符串之前的第一个字符,你只需要说

loc = cleaned.indexOf(remove) - 1;