【问题标题】:Copying characters from a String in an array into a new array将数组中的字符串中的字符复制到新数组中
【发布时间】:2017-03-23 22:42:06
【问题描述】:

我正在编写一个程序来测试数组中的字符串是否为回文。
我正在尝试从一个数组中取出字符串并取出任何空格或其他字符,以便它只是字母或数字。
然后取出“干净”的字符串并将它们存储到一个新数组中。
我用这种方法得到的错误是它说第 4 行的左侧需要一个变量,但我已经将它声明为一个字符串数组。

这是我到目前为止所得到的。

for (i = 0; i < dirty.length; i++) {
        for (int j = 0; j < dirty[i].length(); j++)
        if (Character.isLetterOrDigit(dirty[i].charAt(j))) {
            clean[i].charAt(j) = dirty[i].charAt(j);
        }
}

编辑:我发现的最简单的解决方案是创建一个临时字符串变量来一次添加一个字符,具体取决于它们是字母还是数字。然后转换为小写,然后存储到一个字符串数组中。这是有效的更改代码:

String clean[] = new String[i]; // 存储脏数组中不为空的元素个数

    for (i = 0; i < dirty.length; i++) {
        if (dirty[i] != null) // Only copy strings from dirty array if the value of the element at position i is not empty
        {
            for (int j = 0; j < dirty[i].length(); j++) {
                if (Character.isLetterOrDigit(dirty[i].charAt(j)))// take only letters and digits
                {
                    temp += dirty[i].charAt(j);// take the strings from the dirty array and store it into the temp variable

                }
            }
            temp = temp.toLowerCase(); // take all strings and convert them to lower case
            clean[i] = temp; // take the strings from the temp variable and store them into a new array
            temp = ""; // reset the temp variable so it has no value
        }
    }

【问题讨论】:

  • dirty 变量类型是什么?
  • 看起来是一个字符串数组
  • 你听说过字符串是不可变的吗?
  • 字符串是不可变的...clean[i].charAt(j)不能被赋值
  • 3 秒差异

标签: java arrays string


【解决方案1】:
String clean = dirty.codePoints()
                    .filter(Character::isLetterOrDigit)
                    .collect(StringBuilder::new, 
                             StringBuilder::appendCodePoint,
                             StringBuilder::append)
                    .toString();

但是,也可以将replaceAll 与适当的正则表达式一起使用以生成仅包含字母和数字的新字符串。

取自here

String clean = dirty.replaceAll("[^\\p{IsAlphabetic}^\\p{IsDigit}]", "");

【讨论】:

    【解决方案2】:

    String.charAt(i) 只返回给定位置的char。您不能为其分配新值。但是您可以将String 更改为chars 的数组,然后您可以根据需要对其进行修改

    char[] dirtyTab = dirty.toCharArray();
    

    【讨论】:

      【解决方案3】:

      您不能修改字符串。它们是不可变的。

      但是,您可以覆盖数组中的值。编写一个方法来清理一个字符串。

      for (i = 0; i < dirty.length; i++) {
          dirty[i] = clean(dirty[i]);
      }
      

      还建议您编写一个单独的方法来检查回文

      【讨论】:

        【解决方案4】:

        字符串是不可变的。您可以使用 StringBuilder 因为它不是不可变的,您可以修改它。在您的情况下,您可以使用 StringBuilder 类的 void setCharAt(int index, char ch) 函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-05
          • 2020-11-04
          相关资源
          最近更新 更多