[Solved] Java convert string to int


Assuming you have a string of digits (e.g. "123"), you can use toCharArray() instead:

for (char c : pesel.toCharArray()) {
    temp += 3 * (c - '0');
}

This avoids Integer.parseInt() altogether. If you want to ensure that each character is a digit, you can use Character.isDigit().


Your error is because str.split("") contains a leading empty string in the array:

System.out.println(Arrays.toString("123".split("")));
[, 1, 2, 3]

Now, there is a trick using negative lookaheads to avoid that:

System.out.println(Arrays.toString("123".split("(?!^)")));
[1, 2, 3]

Although, in any case, I would prefer the approach shown above.

4

solved Java convert string to int