Comment puis-je convertir une corde à un int en Java

Mots clés : javastringinttype-conversionjava

meilleur 5 Réponses Comment puis-je convertir une corde à un int en Java

vote vote

94

String myString = "1234"; int foo = Integer.parseInt(myString); 
int foo; try {    foo = Integer.parseInt(myString); } catch (NumberFormatException e) {    foo = 0; } 
import com.google.common.primitives.Ints;  int foo = Optional.ofNullable(myString)  .map(Ints::tryParse)  .orElse(0) 
vote vote

84

Integer x = Integer.valueOf(str); // or int y = Integer.parseInt(str); 
vote vote

80

int foo; String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception try {       foo = Integer.parseInt(StringThatCouldBeANumberOrNot); } catch (NumberFormatException e) {       //Will Throw exception!       //do something! anything to handle the exception. }  try {       foo = Integer.parseInt(StringThatCouldBeANumberOrNot2); } catch (NumberFormatException e) {       //No problem this time, but still it is good practice to care about exceptions.       //Never trust user input :)       //Do something! Anything to handle the exception. } 
vote vote

61

public static int strToInt(String str){     int i = 0;     int num = 0;     boolean isNeg = false;      // Check for negative sign; if it's there, set the isNeg flag     if (str.charAt(0) == '-') {         isNeg = true;         i = 1;     }      // Process each character of the string;     while( i < str.length()) {         num *= 10;         num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).     }      if (isNeg)         num = -num;     return num; } 
vote vote

50

int num = NumberUtils.toInt("1234"); 

Questions similaires