how to convert string to space separated int in java

how to convert string to space separated int in java

To convert a string to a space-separated list of int values in Java, you can use the split method of the String class to split the string into an array of substrings based on the space character, and then use a loop to iterate over the elements of the array and use the Integer.parseInt method to parse each element into an int value.

Here is an example of how you can use the split and Integer.parseInt methods to convert a string to a space-separated list of int values in Java:

refer to‮l:‬autturi.com
String s = "1 2 3 4 5";
int[] intArray = new int[5];
String[] stringArray = s.split(" ");
for (int i = 0; i < stringArray.length; i++) {
  intArray[i] = Integer.parseInt(stringArray[i]);
}

This code defines a String variable called s and assigns it a string of space-separated integers, and then defines an int array called intArray with a size of 5. It then uses the split method to split the s string into an array of substrings based on the space character, and stores the resulting array in a String array called stringArray. It then uses a for loop to iterate over the elements of the stringArray, and uses the Integer.parseInt method to parse each element into an int value, which is then stored in the corresponding element of the intArray.

The split method takes a regular expression as an argument and returns an array of substrings that are delimited by the regular expression. In this example, the regular expression is a space character, so the split method splits the string into substrings based on the space character.

The Integer.parseInt method takes a string as an argument and returns the equivalent int value. If the string cannot be parsed into an int value, the method will throw a NumberFormatException. You can catch this exception if you need to handle invalid input gracefully.

Note that the Integer.parseInt method only works for strings that contain numeric values in decimal format. If the string contains a numeric value in a different format, such as binary, octal, or hexadecimal, you will need to use a different method to parse the value.

For example, to parse a string that contains a binary number, you can use the Integer.parseInt method with the second argument set to 2, like this:

int value = Integer.parseInt("1010", 2);

This code parses the string "1010" as a binary number and returns the equivalent int value, which is 10.

Created Time:2017-11-01 12:05:15  Author:lautturi