我有以下代码:
如果我这样做
作为结果,
我需要
有其他替代方法吗?
String[] alphabet = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q","r", "s", "t", "u", "v", "w", "x", "y", "z"};
如果我这样做
String str = "aa";
for(int i=0;i<str.length();i++) {
chars.add(Arrays.asList(alphabet).indexOf(str.charAt(i)));
}
chars 中的值为
0 = -1
1 = -1
作为结果,
Arrays.asList(alphabet).indexOf(str.charAt(i))
返回的是'a'97而不是"a",因此无法匹配,导致返回-1。我需要
Arrays.asList(alphabet).indexOf(str.charAt(i))
返回"a",这就是我认为charAt
返回的内容,即仅为"a"而不是'a' 97。有其他替代方法吗?
Arrays.asList(alphabet).indexOf(str.charAt(i))
返回的是 'a' 吗?看起来更像是-1
。 - user85421char
是一种整数类型(有点像),你可以对它进行数学运算:str.charAt(i) - 'a'
将返回0表示a
,1表示b
,...上述代码中不需要数组/列表-或者例如'b' - 'a' == 1
。 - user85421