【问题标题】:Remove spaces using substring使用子字符串删除空格
【发布时间】:2021-12-01 13:49:32
【问题描述】:

我有这个:

private String remove_spaces(String s){
    s = s.trim();
    String updated = "";
    for (int i = 0;  i < s.length(); i++) {
        String tester = s.substring(i, i + 1);
        String space = " ";
        boolean isSpace = tester.equals(space);
        if (isSpace = false)
            updated += tester;
    }
    return updated;
}

它会抛出一个StringIndexOutOfBounds,我不明白为什么。为什么?

【问题讨论】:

标签: java substring indexoutofboundsexception removing-whitespace


【解决方案1】:

您遇到了index out of bounds 错误,因为您试图达到一个大于数组实际长度的索引

String tester = s.substring(i,i + 1);

我建议使用这样的 if 子句

private String remove_spaces(String s) {
    s = s.trim();
    String updated = "";
    String tester = "";
    for (int i = 0;  i < s.length(); i++) {
        if (i != s.length-1) {
            tester = s.substring(i, i + 1);
        }else{
            tester = s.substring(i);
        }
        if (!tester.equals(" ")) {
            updated += tester;
        }
    }
    return updated;
}

【讨论】:

    【解决方案2】:

    您需要== 进行比较,而= 是替换运算符。

    if (isSpace == false)
    

    此外,您可以使用!(=not) 来缩短您的代码,如下所示:

    private String remove_spaces(String s) {
        s = s.trim();
        String updated = "";
        for (int i = 0;  i < s.length(); i++) {
            String tester = s.substring(i, i + 1);
            if (!tester.equals(" ")) {
                updated += tester;
            }
        }
        return updated;
    }
    

    【讨论】:

      【解决方案3】:

      在 Java 中删除字符串中空格的更好方法是

      str = str.replace(" ","");
      

      但是如果你想要类似于你的代码的东西,试试下面的,我想 substring 不需要我们可以使用 charAt

      private static String remove_spaces(String s) {
          s = s.trim();
          StringBuilder updated = new StringBuilder();
          for (int i = 0;  i < s.length(); i++) {
            Character tester = s.charAt(i);
            if (!tester.equals(' ')) {
              updated.append(tester);
            }
          }
          return updated.toString();
        }
      

      【讨论】:

        猜你喜欢
        • 2019-10-23
        • 2019-11-05
        • 2011-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        相关资源
        最近更新 更多