In this article, we will discuss how we will convert a string array into an int array. You can convert a string to an integer by using the parseInt () method of class Integer. To convert a string array to an array of integers, convert each element to integer and fill the integer array with them.
title: "Convert string array to int array java"
tags: java
canonical_url: https://kodlogs.com/blog/2150/convert-string-array-to-int-array-java
Example
import java.util.Arrays;
public class StringToIntegerArray {
public static void main (Strng args [ ] {.
String [ ] str = { "1134", "056", "892", "924"};
int size = str.length;
int [ ] arr = new int [size];
for (int i = 0; i <size; i ++) {
arr [i] = Integer.parseInt (str [i]);
}
System.out.println (Arrays.toString (arr));
}
}
Output
[ 1134, 056 , 892 , 924 ]
If we want to convert the string to a primitive data type to int, we are here with a wrapper class, the conversion would be like this
convert class
{
public static void main (Strng args [ ]) {
String str = new String ( "20");
int i = Integer. parseInt (str);
System.out.println (i);
}
}
when this case convert the string to an integer array
Steps will be:
Accept String.
converted to a string as a string array using the split () uses the space as a delimiter.
The wrapper class has provided us with some packages (java.lang.Integer) and will be using parseInt () for each element in the array string.
Store in the integer array :-)
convert class
{
public static void main (String [] args)
{
String str = new String ( "20 30 40 50"); // enter new string
String [] s = str.split ( ""); // this is an array of strings
int [] arr = new int [s.length]; // create a new array of the type int
for (int i = 0; i <s.length; i ++) {
arr [i] = Integer.parseInt (s [i]); // parse each string integer
System.out.println (arr [i]);}
}
}
Output:
20
30
40
50
Hope that it will help you.
Top comments (0)