web-dev-qa-db-ja.com

Integer.parseInt(string)は実際にどのように機能しますか?

最近この質問をされましたが、答えがわかりませんでした。高レベルから、誰かがどのようにJavaが文字/文字列を取り、それをintに変換するかを説明できます。

どうもありがとう

カール

編集:他の言語も同様のことを行うかどうかを知っておくと良いでしょう。

28
Karl

通常、これは次のように行われます。

  • 0の初期化結果
  • 文字列の各文字に対してこれを行います
    • 結果=結果* 10
    • 文字から数字を取得します( '0'は48 ASCII(または0x30)なので、文字から数字を減算しますASCII数字を取得するコード))
    • 結果に数字を追加します
  • 結果を返す

編集:これは、10を正しいベースに置き換え、対応する文字からの数字の取得を調整する場合、すべてのベースで機能します(10未満のベースの場合はそのまま動作しますが、少し調整する必要があります) 16進数のようなより高い基数の場合-文字は数字と7文字で区切られているため)。

編集2:文字から数値への変換:文字 '0'から '9'にはASCII値48から57(ヘキサでは0x30から0x39)があるため、順番に文字をその数値に変換するには、単純な減算が必要です。通常、次のように行われます(ここでordは、文字のASCIIコードを与える関数です):

digit = ord(char) - ord('0')

数字の基数が大きい場合、文字は「数字」として使用されますが(16進数ではA-F)、文字は65(0x41 16進数)から始まります。これは、考慮すべきギャップがあることを意味します。

digit = ord(char) - ord('0')
if digit > 9 then digit -= 7

例: 'B'は66であるため、ord( 'B')-ord( '0')=18。18は9より大きいため、7を減算し、最終結果は11-'digit' Bの値になります。 。

ここでもう1つ注意する点があります。これは大文字でのみ機能するため、最初に数字を大文字に変換する必要があります。

42
rslite

Java APIのソースコードは自由に利用できます。ここにparseInt()メソッドがあります。これは、多くの例外的なコーナーケースを処理する必要があるため、かなり長いです。

public static int parseInt(String s, int radix)
    throws NumberFormatException
{
    if (s == null) {
        throw new NumberFormatException("null");
    }

if (radix < Character.MIN_RADIX) {
    throw new NumberFormatException("radix " + radix +
                    " less than Character.MIN_RADIX");
}

if (radix > Character.MAX_RADIX) {
    throw new NumberFormatException("radix " + radix +
                    " greater than Character.MAX_RADIX");
}

int result = 0;
boolean negative = false;
int i = 0, max = s.length();
int limit;
int multmin;
int digit;

if (max > 0) {
    if (s.charAt(0) == '-') {
    negative = true;
    limit = Integer.MIN_VALUE;
    i++;
    } else {
    limit = -Integer.MAX_VALUE;
    }
    multmin = limit / radix;
    if (i < max) {
    digit = Character.digit(s.charAt(i++),radix);
    if (digit < 0) {
        throw NumberFormatException.forInputString(s);
    } else {
        result = -digit;
    }
    }
    while (i < max) {
    // Accumulating negatively avoids surprises near MAX_VALUE
    digit = Character.digit(s.charAt(i++),radix);
    if (digit < 0) {
        throw NumberFormatException.forInputString(s);
    }
    if (result < multmin) {
        throw NumberFormatException.forInputString(s);
    }
    result *= radix;
    if (result < limit + digit) {
        throw NumberFormatException.forInputString(s);
    }
    result -= digit;
    }
} else {
    throw NumberFormatException.forInputString(s);
}
if (negative) {
    if (i > 1) {
    return result;
    } else {    /* Only got "-" */
    throw NumberFormatException.forInputString(s);
    }
} else {
    return -result;
}
}
25

「ハイレベル」として、あなたが何を探しているのか分かりません。試してみます:

  • 文字列を取得し、すべての文字を1つずつ解析します
  • 合計0から始めます
  • 0〜9の場合、total = (total x 10) + current
  • 完了すると、合計が結果になります
8
KLE
public class StringToInt {

    public int ConvertStringToInt(String s) throws NumberFormatException
    {
        int num =0;
        for(int i =0; i<s.length();i++)
        {
            if(((int)s.charAt(i)>=48)&&((int)s.charAt(i)<=59))
            {
                num = num*10+ ((int)s.charAt(i)-48);
            }
            else
            {
                throw new NumberFormatException();
            }

        }
        return num; 
    }

    public static void main(String[]args)
    {
        StringToInt obj = new StringToInt();
        int i = obj.ConvertStringToInt("1234123");
        System.out.println(i);
    }

}
6
javaMan
  • 文字列の長さを見つける(s)(たとえばmaxSize)
  • _result = 0_を初期化します
  • ループの開始_( int j=maxSize, i =0 ; j > 0; j--, i++)_
  • int digit = Character.digit(s.charAt(i))
  • result= result + digit * (10 power j-1)
  • 終了ループ
  • 結果を返す
3
zkarthik

これはparse intの私のシンプルな実装です

public static int parseInteger(String stringNumber) {
    int sum=0;
    int position=1;
    for (int i = stringNumber.length()-1; i >= 0 ; i--) {
       int number=stringNumber.charAt(i) - '0';
       sum+=number*position;
       position=position*10;

    }
    return sum;
}
1

ここに私が思いついたものがあります(注:アルファベットのチェックは行われません)

int convertStringtoInt(String number){

    int total =0;
    double multiplier = Math.pow(10, number.length()-1);
        for(int i=0;i<number.length();i++){

            total = total + (int)multiplier*((int)number.charAt(i) -48);
            multiplier/=10;

        }

        return total;
    }
0
Shishir Shetty