簡體   English   中英

我可以在Java中乘以charAt嗎?

[英]Can I multiply charAt in Java?

當我嘗試乘以charAt時,我收到“大”數字:

String s = "25999993654";
System.out.println(s.charAt(0)+s.charAt(1));

結果:103

但是,當我只想接收一個號碼時,就可以了。

在JAVA文檔中:

the character at the specified index of this string. The first character is at index 0.

因此,我需要說明或解決方案(我認為我應該將string轉換為int,但在我看來這是不必要的工作)

char整數類型 在您的示例中, s.charAt(0)的值是數字50的char版本( '2'的字符代碼)。 s.charAt(1)(char)53 當您在它們上使用+時,它們將轉換為整數,最終得到103(而不是100)。

如果您嘗試使用數字 25 ,是的,則必須解析它們。 或者,如果您知道它們是標准ASCII樣式的數字(字符代碼48至57,包括端值),則可以從中減去48(因為48是'0'的字符代碼)。 甚至更好的是,正如Peter Lawrey在其他地方指出的那樣,請使用Character.getNumericValue ,它可以處理更大范圍的字符。

是的-您應該解析提取的數字或使用ASCII圖表功能並減去48:

public final class Test {
    public static void main(String[] a) {
        String s = "25999993654";
        System.out.println(intAt(s, 0) + intAt(s, 1));
    }

    public static int intAt(String s, int index) {
        return Integer.parseInt(""+s.charAt(index));
        //or
        //return (int) s.charAt(index) - 48;
    }
}

暫無
暫無

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

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