簡體   English   中英

charAt() 方法如何從字符串中獲取數字並將它們放入 Java 中的新字符串中?

[英]How does the charAt() method work with taking numbers from strings and putting them into new strings in Java?

public String getIDdigits()
    {
        String idDigits = IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1) + "";
        return idDigits;
    }

在這個簡單的方法中,其中 IDnum 是一個由數字組成的 13 位字符串並且是一個 class 變量,給定的 output 絕不是我所期望的。 對於像 1234567891234 這樣的 ID 號,我希望在 output 中看到 14,但是 output 始終是三位數,例如 101。無論我使用什么 ID 號,它總是以 3 開頭的數字.我認為使用空引號可以避免取 Ascii 值的問題,但我似乎仍然會出錯。 請有人能解釋一下 charAt() 在這個意義上是如何工作的嗎?

嘗試這個。

public String getIDdigits()
    {
        String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);
        return idDigits;
    }

當你第一次添加一個空時,如果你把它放在最后,它會像String一樣添加char ,它首先添加數字模式(ASCII),然后 convert 將其轉換為String

您正在從String中獲取char類型,然后使用+運算符,在這種情況下,它的行為是將 ASCII 數值加在一起。

例如,在您的代碼中使用 char '1' ,然后是 char '4'

IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

編譯器將其解釋為其 ASCII 十進制等價物並添加這些

49 + 52 = 101

這就是您的 3 位數號碼的來源。

通過在連接它們之前將它們轉換回字符串來消除這種情況......

String.valueOf(<char>);

或者

"" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1)

您必須更明確地了解字符串連接,因此像這樣解決您的語句:

String idDigits = "" + IDnum.charAt(0) + IDnum.charAt(IDnum.length() - 1);

添加 Java 字符、短褲或字節的結果是一個 int:

暫無
暫無

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

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