String.charAt() 在 java 中返回奇怪的结果

我有以下代码


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)));

 }

字符中的值是


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


任何选择?


一只萌萌小番薯
浏览 314回答 3
3回答

翻翻过去那场雪

str.charAt(i)返回 achar 和ListcontainsString元素。作为char是不是String和String.equals()而Character.equals()不是他们(间互操作"a".equals('a')和Character.valueOf('a').equals("a")回报false),stringList.indexOf(anyChar)将始终返回-1。你可以替换:chars.add(Arrays.asList(alphabet).indexOf(str.charAt(i)));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^----- List<String>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^----- char (that will be boxed to Character)经过 :chars.add(Arrays.asList(alphabet).indexOf(String.valueOf(str.charAt(i))));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^----- List<String>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^----- String比较String有String。或作为替代方案比较char与char依靠char[],而不是String[]如:char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',&nbsp; &nbsp; &nbsp; &nbsp; 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};&nbsp;通过这种方式,这将编译得很好:List<Character> charList = IntStream.range(0, alphabet.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> alphabet[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());chars.add(charList.indexOf(str.charAt(i)));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^------- List<Character>&nbsp; &nbsp; &nbsp; ^------ char (that will be boxed to Character)不是您的直接问题,而是List在每次迭代中创建相同的问题是不合逻辑的,而且有点浪费。在循环之前实例化一次更有效:List<String> alphabetList = Arrays.asList(alphabet);String str = "aa";for(int i=0;i<str.length();i++) {&nbsp; &nbsp;chars.add(alphabetList.indexOf(String.valueOf(str.charAt(i))));}

隔江千里

需要注意的是,字符和字符串在 Java 中不是一回事。Achar是一个原始的数字类型,它的文字使用单引号(例如'a')给出。字符串是逻辑上由多个字符组成的引用类型。最简单的解决方案是使您的字母表成为单个字符串:String&nbsp;alphabet&nbsp;=&nbsp;"abcdef...";并在查找索引时扫描该字符串:&nbsp;chars.add(alphabet.indexOf(str.charAt(i)));请注意,这现在使用String.indexOf而不是List您之前使用的indexOf 方法。或者,转换alphabet为字符数组:char[]&nbsp;alphabet&nbsp;=&nbsp;new&nbsp;char[]&nbsp;{'a',&nbsp;'b',&nbsp;/*&nbsp;...&nbsp;*/&nbsp;};

慕的地8271018

Arrays.asList(alphabet)是一个List<String>。它不包含任何类型Character。如果要查找由该单个字符组成的字符串,请构建该单个字符的字符串:Arrays.asList(alphabet).indexOf(Character.toString(str.charAt(i)))要么Arrays.asList(alphabet).indexOf(str.substring(i,&nbsp;i+1))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java