簡體   English   中英

StringBuilder的indexOf()不返回任何內容

[英]indexOf() of StringBuilder doesn't return anything

    StringBuilder builder = new StringBuilder();
    builder.setLength(10);
    builder.append("d");        
    System.out.println(builder.length() + "\t" + builder.toString() + "\t" + builder.indexOf("d"));

輸出:

11 

問題:

Why indexOf() doesn't return anything.

我的理解:

 As per my understanding, it should return 10, since StringBuilder is counting the "d" as part of its length in length().
 But in case if "d" is not part of string hold by StringBuilder then, it should return -1 and length should be 10.

如果你看一下StringBuilder#setLength(int newLength)的文檔StringBuilder#setLength(int newLength)

如果newLength參數大於或等於當前長度,則會附加足夠的空字符('\\ u0000'),以便length成為newLength參數。

這就是為什么在設置長度后附加“d”時,它會放在10個空字符之后


問:為什么indexOf()不返回任何內容。

它確實返回一個值,即10 ,因為索引是從0開始的 這是代碼的輸出。

11           d  10         // the 10 represents the index of d
^-length     ^-10 null chars followed by d

您沒有獲得輸出的原因可能是您的控制台不支持null字符。 這就是為什么當它遇到空字符\ ,它只會停止在控制台中打印值。 嘗試使用支持Unicode字符打印的eclipse。

示例快照

輸出快照

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM