String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Answer from Saul on Stack OverflowString arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Using Java 8's stream library, we can make this a one-liner (albeit a long line):
String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).
How to convert a String into an Integer[] array in Java? - Stack Overflow
Converting a String array into an int Array in java - Stack Overflow
java - Is String to int Array conversion possible? - Stack Overflow
Java- Converting a string of numbers separated by spaces into an array?
You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
With the Arrays.stream() alternative as
int [] v = Arrays.stream(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
However much better for parsing bigger chunks of text is
int [] v = Pattern.compile(",\\s+").splitAsStream(line)
.mapToInt(Integer::parseInt)
.toArray();
As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.
See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.
I'd split the string, stream the array, parse each element separately and collect them to an array:
int[] result = Arrays.stream(str.split(" ")).mapToInt(Integer::parseInt).toArray();
if they are separated by spaces you can convert them one by one like this
String array = "19 35 91 12 36 48 59";
// separate them by space
String[] splited = array.split(" ");
// here we will save the numbers
int[] numbers = new int[splited.length];
for(int i = 0; i < splited.length; i++) {
numbers[i] = Integer.parseInt(splited[i]);
}
System.out.println(Arrays.toString(numbers));
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next βΌ:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
βΌ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
βββββββββ
Notes
ββ1. Lambda Expressions in The Java Tutorials.
ββ2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
Your expected output would not even seem to need any integer to string conversion:
int n = scan.nextInt();
for (int i=0; i < n; i++) {
if (i > 0) System.out.print(" ");
System.out.print(1 + i % 9);
}
For an input of n = 12, this prints:
1 2 3 4 5 6 7 8 9 1 2 3
You can't pass the whole array to parseInt(). You need to parse each element individually:
int[] c = Arrays.stream(s.split(""))
.mapToInt(Integer::parseInt)
.toArray();
Or the old-fashioned way:
String[] chars = s.split("");
int[] c = new int[chars.length];
for (int i = 0; i < c.length; i++) {
c[i] = Integer.parseInt(chars[i]);
}
For example, I have String input which will look something like "5 6 6" but I need it to be converted into an array. What is the easiest way to do this? I have messed around with .split and .parseInt but have not come to any solid conclusions. Thanks!