sirve que parsestring para java string parsing

java - que - ¿Cómo funciona Integer.parseInt(cadena) en realidad?



parsestring java (7)

Se le hizo esta pregunta recientemente y no sabía la respuesta. Desde un nivel alto alguien puede explicar cómo Java toma un carácter / Cadena y lo convierte en un int.

Muchas gracias

Karl

Editar: También sería bueno saber si otros idiomas hacen un tipo similar de cosas también.


El código fuente de la API de Java está disponible gratuitamente. Aquí está el método parseInt (). Es bastante largo porque tiene que manejar muchos casos excepcionales y de esquina.

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; } }


Esto es lo que se me ocurrió (Nota: no se realizan controles para los alfabetos)

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; }


No estoy seguro de lo que estás buscando, como "alto nivel". Lo probaré:

  • tomar la secuencia, analizar todos los caracteres uno por uno
  • comenzar con un total de 0
  • si está entre 0 y 9, total = (total x 10) + current
  • cuando termine, el total es el resultado

Por lo general, esto se hace así:

  • Resultado inicial con 0
  • para cada personaje en la cadena haga esto
    • resultado = resultado * 10
    • obtener el dígito del personaje (''0'' es 48 ASCII (o 0x30), así que resta eso del código ASCII del personaje para obtener el dígito)
    • agrega el dígito al resultado
  • resultado de devolución

Editar : Esto funciona para cualquier base si reemplaza 10 con la base correcta y ajusta la obtención del dígito del carácter correspondiente (debería funcionar igual que para bases inferiores a 10, pero necesitaría un poco de ajuste para bases más altas, como hexadecimal, ya que las letras están separadas de los números por 7 caracteres).

Edición 2 : conversión de valor de Char a dígito: los caracteres ''0'' a ''9'' tienen valores ASCII 48 a 57 (0x30 a 0x39 en hexa), por lo que para convertir un carácter a su valor de dígito, se necesita una resta simple. Por lo general, se hace así (donde ord es la función que da el código ASCII del personaje):

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

Para bases de números más altos, las letras se usan como ''dígitos'' (AF en hexa), pero las letras comienzan desde 65 (hexadecimal 0x41), lo que significa que hay una brecha que tenemos que tener en cuenta:

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

Ejemplo: ''B'' es 66, entonces ord (''B'') - ord (''0'') = 18. Como 18 es mayor que 9, restamos 7 y el resultado final será 11 - el valor del ''dígito'' B .

Una cosa más a tener en cuenta aquí: esto funciona solo para letras mayúsculas, por lo que el número primero debe convertirse a mayúsculas.


esta es mi implementación simple de 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; }


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); } }


  • Encuentre la longitud de la (s) Cadena (s) (digamos maxSize)
  • Initialize result = 0
  • begin loop (int j = maxSize, i = 0; j> 0; j--, i ++)
  • int digit = Character.digit (s.charAt (i))
  • resultado = resultado + dígito * (10 potencia j-1)
  • ciclo final
  • resultado de devolución