将数组中的字符串复制到新数组中
问题描述:
我正在制作一个程序来测试数组中的字符串是否是回文。
我想从一个数组中取出字符串,并取出任何空格或其他字符,以便它只是字母或数字。
然后把“干净的”字符串存储到一个新的数组中。
我用这种方法得到的错误是它说第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
}
}
答
String.charAt(i)
只是在给定的位置返回char
。您无法为其分配新的值。但你可以String
更改为char
秒的数组,然后你可以修改它,只要你想
char[] dirtyTab = dirty.toCharArray();
答
您不能修改字符串。它们是不可改变的。
但是,您可以覆盖数组中的值。编写一个方法来清理一个字符串。
for (i = 0; i < dirty.length; i++) {
dirty[i] = clean(dirty[i]);
}
而且其建议你写一个单独的方法来检查回文以及
答
字符串是不可变的。你可以使用StringBuilder,因为它不是不可变的,你可以修改它。在你的情况下,你可以使用StringBuilder类的void setCharAt(int index, char ch)
函数。
答
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}]", "");
什么是'dirty'变量类型? –
看起来是一串字符串 –
你是否听说过字符串是不可变的? –