简体   繁体   English

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

[英]String.charAt() returning weird result in java

i have the following code 我有以下代码

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"};

if i do 如果我做

 String str = "aa";
 for(int i=0;i<str.length();i++) {
    chars.add(Arrays.asList(alphabet).indexOf(str.charAt(i)));
 }

the values in chars are 字符中的值是

0 = -1
1 = -1 

as the result returned by Arrays.asList(alphabet).indexOf(str.charAt(i)) is 'a'97 and not "a" hence its not matching due to which -1 is being returned 由Arrays.asList(字母)返回的结果.indexOf(str.charAt(i))是'a'97而不是“a”因此它不匹配,因为返回-1

I need Arrays.asList(alphabet).indexOf(str.charAt(i)) to return "a" that's what i thought charAt returns which is just "a" and not this 'a' 97 我需要Arrays.asList(alphabet).indexOf(str.charAt(i))返回“a”,这就是我认为charAt返回的只是“a”而不是'a'97

any alternative ? 任何替代?

str.charAt(i) returns a char and the List contains String elements. str.charAt(i)返回一个charList包含String元素。
As a char is not a String and String.equals() and Character.equals() are not interoperable between them ( "a".equals('a') and Character.valueOf('a').equals("a") return false ), stringList.indexOf(anyChar) will always return -1 . 因为char不是String而且String.equals()Character.equals()在它们之间不可互操作( "a".equals('a')Character.valueOf('a').equals("a") return false ), stringList.indexOf(anyChar)将始终返回-1

You could replace : 你可以替换:

chars.add(Arrays.asList(alphabet).indexOf(str.charAt(i)));
                ^----- List<String>          ^----- char (that will be boxed to Character)

by : 通过:

chars.add(Arrays.asList(alphabet).indexOf(String.valueOf(str.charAt(i))));
                ^----- List<String>             ^----- String

to compare String with String . StringString进行比较。

Or as alternative compare char with char by relying on char[] instead of String[] such as : 或者作为替代,通过依赖char[]而不是String[]来比较charchar ,例如:

char[] alphabet = new char[] { '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'}; 

In this way this will compile fine : 通过这种方式,这将编译正常:

List<Character> charList = IntStream.range(0, alphabet.length)
                                          .mapToObj(i -> alphabet[i])
                                          .collect(Collectors.toList());
chars.add(charList.indexOf(str.charAt(i))); 
            ^------- List<Character>      ^------ char (that will be boxed to Character)

Not your direct question but creating the same List at each iteration is not logical and is a little some waste. 不是你的直接问题,但在每次迭代时创建相同的List是不合逻辑的,有点浪费。
Instantiating it once before the loop is more efficient : 在循环之前实例化一次更有效:

List<String> alphabetList = Arrays.asList(alphabet);
String str = "aa";
for(int i=0;i<str.length();i++) {
   chars.add(alphabetList.indexOf(String.valueOf(str.charAt(i))));
}

It's important to note that chars and Strings are not the same thing in Java. 值得注意的是,字符和字符串在Java中并不相同。 A char is a primitive, numerical type, and its literals are given using single quotes (eg 'a' ). char是原始的数字类型,其文字是使用单引号(例如'a' )给出的。 A String is a reference type that logically consists of multiple characters. String是一种逻辑上由多个字符组成的引用类型。

The simplest solution would be to make your alphabet a single string: 最简单的解决方案是使您的字母表成为单个字符串:

String alphabet = "abcdef...";

and to scan that string when finding the index: 并在查找索引时扫描该字符串:

 chars.add(alphabet.indexOf(str.charAt(i)));

Note that this now uses String.indexOf and not the List indexOf method that you were using before. 请注意,现在使用String.indexOf而不是之前使用的List indexOf方法。

Alternatively, convert alphabet to be an array of characters: 或者,将alphabet转换为字符数组:

char[] alphabet = new char[] {'a', 'b', /* ... */ };

Arrays.asList(alphabet) is a List<String> . Arrays.asList(alphabet)List<String> It does not contain anything of type Character . 它不包含任何Character类型。

If you want to look for a String consisting of that single character, build a string of that single character: 如果要查找由该单个字符组成的字符串,请构建该单个字符的字符串:

Arrays.asList(alphabet).indexOf(Character.toString(str.charAt(i)))

or 要么

Arrays.asList(alphabet).indexOf(str.substring(i, i+1))

This is because char != string in java, 这是因为java中的char != string

So to resolve your problem, 所以要解决你的问题,

Arrays.<String>asList(alphabet).indexOf(Character.toString(str.charAt(i)))

Now you will get your output as expected. 现在,您将按预期获得输出。

So the problem was that you created List of String and was looking for a character in string so java was unable to find it. 所以问题是你创建了List of String并且正在查找字符串中的字符,因此java无法找到它。 So it returned -1 . 所以它返回-1

You could convert the String to a character array and iterate through that: 您可以将String转换为字符数组并迭代:

    List<Integer> indices = new ArrayList<>();

    String str = "abc";

    for ( Character character : str.toCharArray() )
    {
        indices.add(Arrays.asList(alphabet).indexOf(character.toString()));
    }

It is possible to do integer operations on char - it is an integral type (displayed as character). 可以对char执行整数运算 - 它是一个整数类型(显示为字符)。 Examples: 'b' - 'a' == 1 , 'c' - 'a' == 2 , and so on. 示例: 'b' - 'a' == 1'c' - 'a' == 2 ,依此类推。 (Actually 'a' == 97 , its Unicode value). (实际上'a' == 97 ,它的Unicode值)。

For the given code, there is no need for the array or a list, it could be written as 对于给定的代码,不需要数组或列表,它可以写成

for (int i=0; i<str.length(); i++) {
    chars.add(str.charAt(i) - 'a');
}

sure the loop can be written as 确保循环可以写成

for (char ch : str.toCharArray()) {
    chars.add(ch - 'a');
}

or even using streams: 甚至使用流:

str.chars().map(ch -> ch - 'a').forEach(chars::add)

missing the type of chars , I just assumed it is List<Integer> 错过了chars的类型,我只是假设它是List<Integer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM