Reputation: 11
I was wondering how would I convert a string
to an int
array.
I created a reader to read from a text file, which consists of two lines.
I am supposed to save each character from the quote into a char
array, and then the second line, consisting of the numbers, is the order number of each char
, and when printed out in that order, it will spell out a phrase.
I used the .hasNextLine
method to first save the two lines into two string variables. Then, I converted the first line into the char
array, and that part is ok but I do not know how to convert the second part into an int
array.
I called the variable holding the second line "numbers" and it contains the string "6 25 11 32 6 11 44......"
How would I convert this into an int
array?
Thanks so much
Upvotes: 0
Views: 11160
Reputation: 536
If your numbers are delimited by spaces like it is described in your post, you can use String.split()
to your advantage.
You can create a method like the following which will convert a String
of integers to an int[]
:
public static int[] stringArrayToIntArray(String intString) {
String[] intStringSplit = intString.split(" "); //Split by spaces
int[] result = new int[intStringSplit.length]; //Used to store our ints
for (int i = 0; i < intStringSplit.length; i++) {
//parse and store each value into int[] to be returned
result[i] = Integer.parseInt(intStringSplit[i]);
}
return result;
}
Which can be called like so:
public static void main(String[] args) {
String intString = "6 25 11 32 6 11 44"; //Original String
int[] intArray = stringArrayToIntArray(intString); //Call our method
}
If you were to iterate through intArray
and print each value with the following:
for (int i : intArray) {
System.out.println(i);
}
You'd get a result of:
run:
6
25
11
32
6
11
44
BUILD SUCCESSFUL (total time: 0 seconds)
Cheers!
Upvotes: 3
Reputation: 18810
You could do something real simple like this:
String[] strArray = input.split(" ");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
Also, you'd want to check for NumberFormatException
using a try..catch
block.
Upvotes: 5