简体   繁体   English

java charAt()方法和代理

[英]java charAt() method and surrogate

I am writing java code and want to know why the output of this code is x . 我正在编写Java代码,想知道为什么此代码的输出为x I was expecting t since it is the 5th letter. 我期待t因为它是第5个字母。

public class StringBufferDemo{
    public static void main(String args[]){
        StringBuffer sb = new StringBuffer("ttsttxctlltnt");
        System.out.println(sb.charAt(5));
    }
}

It's because in java a StringBuffer object is indexed starting at 0. 1 st char at position 0, 2 nd char at position 1, etc... 这是因为在Java中, StringBuffer对象的索引从0开始。位置0的第一个字符,位置1的第二个字符, 依此类推...

String ------ "t t s t t x c t l l"
ArrayIndex --  0 1 2 3 4 5 6 7 8 9

索引从0开始而不是1。因此,在字符串“ ttsttxctlltnt”中,将打印位置5(0,1,2,3,4,5)处的字符,即“ x”。

索引从0开始,所以第5个字符的字符是x ...如果您想将t作为输出,请尝试以下操作

 System.out.println(sb.charAt(4));

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

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