【问题标题】:String iteration with numbers at the end (Beginner)以数字结尾的字符串迭代(初学者)
【发布时间】:2023-03-15 06:06:01
【问题描述】:

我有一个代码可以“删除”一个句子中连续出现多次的所有字符。例如:

“Thiiis iiis aaa 测试”

我使用charAt()length() 方法(这是大学的任务,我只能使用这两种方法)。 在某种程度上它运作良好,但我的问题是:

为什么我在句子末尾看到数字?谁能告诉我我的代码是否错误或哪里错误?

这是一个测试19212325272

这是我用于此的代码:

public static String reduce(String w) {
    String result = "";
    for (int i = 0; i < w.length() - 1; i++) {
        if(w.charAt(i) == w.charAt(i + 1)) {
            w += w.length() - 1;
        }
        else {
            result += w.charAt(i);
        } 
    }
    return result;
}

谢谢!

【问题讨论】:

  • 就是因为这个w += w.length() - 1;。当您看到相同的两个相邻字符时,您会尝试做什么?
  • 第一个字符之后的字符应该被删除,直到到达下一个字符。
  • 测试中有2个t是有问题
  • 你需要删除字符而不是添加它。

标签: java methods iteration


【解决方案1】:

这是因为w += w.length() - 1。你不需要那个。

修改后的代码:-

public static String reduce(String w) {
    if (w == null) return null;         // in case if w is NULL
    String result = "";
    result += w.charAt(0);
    for (int i = 1; i < w.length(); i++) {
        if (w.charAt(i - 1) != w.charAt(i)) {
            result += w.charAt(i);
        }
    }
    return result;
}

输出:-

Thiiis iiis aaa tesst
This is a test

【讨论】:

    【解决方案2】:

    这是因为 w += w.length() - 1 当有两个相同的字符被添加到 w 时,它的长度会发生变化。当您删除它时(并在 for 循环后添加检查最后一个字符是否与之前的相同),则此代码可以正常工作

    【讨论】:

      【解决方案3】:

      您根本不需要if 条件。以下程序删除重复字符:

      public static String reduce(String w) {
          // make sure w is not null
          if (w == null) return null;
      
          String result = Character.toString(w.charAt(0));
          for (int i = 1; i < w.length(); i++) {
              if(w.charAt(i) != w.charAt(i - 1)) {
                  result += w.charAt(i);
              }
          }
          return result;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-09
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多