【发布时间】: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 秒差异