如何在 Java 中将字符串转换为 int?

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

转载于:https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java

30个回答

String myString = "1234";
int foo = Integer.parseInt(myString);

See the Java Documentation for more information.

csdnceshi69
YaoRaoLov If you use Integer.parseInt prepare to put it inside a try catch block since this will throw are NumberFormat or InputMismatch Exception if it is not a valid number. Then in that case have proper exception handling at the catch block level. Otherwise as mentioned below you can also use the Integer class and then convert it to int.
接近 2 年之前 回复
weixin_41568183
零零乙 This method also throws exception when string is not a parsable integer in base 10. Use overloaded method to work in other bases. e.g. Integer.parseInt("1001", 8); for base 8. Source.
大约 2 年之前 回复
csdnceshi64
游.程 You could check if the string is a Number first: stackoverflow.com/questions/1102891/…
2 年多之前 回复
csdnceshi73
喵-见缝插针 especially if using BIGINT field in a PostgreSQL auto incremented primary key field for instance. Much safer to use long
2 年多之前 回复
csdnceshi74
7*4 In addition to catching a NumberFormatException, the user should also be careful about the length of the strings they're passing in; if they're long enough to overflow an integer, they might want to consider using Long::parseLong instead.
2 年多之前 回复
csdnceshi67
bug^君 This will throw NumberFormatException if input is not a valid number.
接近 5 年之前 回复

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

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

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

csdnceshi74
7*4 - See docs.oracle.com/javase/8/docs/api/java/util/regex/… - a regular expresssion pattern of "([0-9]+)" will "capture" the first sequence of one or more digits one through nine. Look at the Matcher class in that package.
大约 2 年之前 回复
csdnceshi68
local-host how can I parse "26263Hello" ? I want to extract 26263 in that case
大约 2 年之前 回复

For example, here are two ways:

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

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

weixin_41568174
from.. i dont get it... valueOf calls itself recursively?
接近 2 年之前 回复
csdnceshi76
斗士狗 valueOf method is just return valueOf(parseInt(string));
接近 6 年之前 回复
csdnceshi68
local-host For the differences between the two methods, see this question
大约 7 年之前 回复

Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

Apart from these above answers, I would like to add several functions:

    public static int parseIntOrDefault(String value, int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(value);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex, endIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

And here are results while you running them:

  public static void main(String[] args) {
    System.out.println(parseIntOrDefault("123", 0)); // 123
    System.out.println(parseIntOrDefault("aaa", 0)); // 0
    System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
    System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
  }

This is Complete program with all conditions positive, negative without using library

import java.util.Scanner;


    public class StringToInt {
     public static void main(String args[]) {
      String inputString;
      Scanner s = new Scanner(System.in);
      inputString = s.nextLine();

      if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
       System.out.println("Not a Number");
      } else {
       Double result2 = getNumber(inputString);
       System.out.println("result = " + result2);
      }

     }
     public static Double getNumber(String number) {
      Double result = 0.0;
      Double beforeDecimal = 0.0;
      Double afterDecimal = 0.0;
      Double afterDecimalCount = 0.0;
      int signBit = 1;
      boolean flag = false;

      int count = number.length();
      if (number.charAt(0) == '-') {
       signBit = -1;
       flag = true;
      } else if (number.charAt(0) == '+') {
       flag = true;
      }
      for (int i = 0; i < count; i++) {
       if (flag && i == 0) {
        continue;

       }
       if (afterDecimalCount == 0.0) {
        if (number.charAt(i) - '.' == 0) {
         afterDecimalCount++;
        } else {
         beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
        }

       } else {
        afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
        afterDecimalCount = afterDecimalCount * 10;
       }
      }
      if (afterDecimalCount != 0.0) {
       afterDecimal = afterDecimal / afterDecimalCount;
       result = beforeDecimal + afterDecimal;
      } else {
       result = beforeDecimal;
      }

      return result * signBit;
     }
    }
csdnceshi64
游.程 No, no one needs it because it is a function inside the JDK, not some third party plugin.
2 年多之前 回复
weixin_41568183
零零乙 some people need this how to do without using Library.
2 年多之前 回复
csdnceshi64
游.程 I can see that, but what is the point not to use a library?
2 年多之前 回复
weixin_41568183
零零乙 yes, we can do but this is without using library
2 年多之前 回复
csdnceshi64
游.程 There is no need to reinvent the wheel, just use Integer.parseInt.
接近 3 年之前 回复

Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

In my opinion, this special case should be handled by returning an Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

Usage:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

While this is still using exceptions for flow control internally, the usage code becomes very clean.

Simply you can try this:

  • Use Integer.parseInt(your_string); to convert a String to int
  • Use Double.parseDouble(your_string); to convert a String to double

Example

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
csdnceshi53
Lotus@ This answer doesn't appear to add anything beyond the answers recommending Integer.parseInt posted a few years earlier (converting String to double would be a different question).
2 年多之前 回复

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length()-2);
 int lastdigitASCII = number.charAt(number.length()-1);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

 double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No "Magic" Expressions such as parseInt
csdnceshi68
local-host I was personally given that restriction when first starting out programming, and also when I had to write (pen/paper) similar interactions in a test. It's uncommon, but it's a method that is easily understood and while not being the most efficient by miles it's a method that works decently enough for small projects. SO.SE is meant to help everyone, not just a few. I provided an alternative method, for those who are starting out by learning how to create a pseudo-algorithm and turning it into an algorithm rather than using premade java expressions. Although I did forget that '0' is cool
4 年多之前 回复
csdnceshi53
Lotus@ It’s not clear what kind of problem this answer tries to solve, first, why anyone should ever have that restriction you describe, second, why you have to look at an ASCII table as you can simply use '0' for the character instead of 48 and never have to bother with its actual numeric value. Third, the entire detour with double values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply is semilastdigit * 10 + lastdigit as learnt in elementary school, when the decimal system was introduced…
4 年多之前 回复
csdnceshi78
程序go Using type double for parsing an integer is not only a bad idea performance-wise. Values like 0.2 are periodic numbers in floating-point representation and cannot be represented precisely. Try System.out.println(0.1+0.2) to see the point -- the result will not be 0.3! Better stick with library code whereever you can, in this case Integer.parseInt().
接近 5 年之前 回复
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐