【问题标题】: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)当 while 循环运行时究竟发生了什么(在 while 循环中做了什么)? (它应该删除子字符串和它后面的字符)
【发布时间】:2018-11-16 23:54:32
【问题描述】:
 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;
}

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

【问题讨论】:

  • indexOfcleaned 中找不到remove 时返回-1。
  • 您可能想了解indexOfsubstring 的工作原理。

标签: java substring indexof


【解决方案1】:

String.substring() 要么返回两个位置之间的部分 ob 字符串(在 cleaned.substring(0, 1) 中,这将是位置 0 和 1 之间的 cleaned 的内容),或者如果你只给该方法 1 个 int-argument ,它会返回您的字符串中位于该位置之后的部分。

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

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

所以while循环会是这样的:

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

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

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

编辑:

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

loc = cleaned.indexOf(remove) - 1;

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2017-02-01
    • 2014-07-16
    相关资源
    最近更新 更多