How to convert a string array to an int array? - java

How do I convert a string like:
"114 214 219"
Into an an int array so I have something like this stored in my int array:
int[] couseNumbers = int[3];
for(int i = 0; i < 3; i++){
courseNumbers[i] = Integer.parseInt(/*get int in the string array*/);
}

Split the String into an array first.
String[] stringArray = "114 214 219".split(" ");
Then in the loop you can access that array:
courseNumbers[i] = Integer.parseInt(stringArray[i])

Try this
String s = "1 2 3";
String array[] = s.split(" "); //Splits the Array by spaces
int a[] = new int[array.length]; //Makes new int array
for(int i=0;i<a.length;i++){
a[i] = Integer.parseInt(array[i]); //Converts String to int
}

Using Java 8 streams.
List<Integer> courseNumbers = Arrays.stream("1123 213 23"
.split(" ")).map(x-> Integer.parseInt(x))
.collect(Collectors.toList());

Answer above by Eduardo Dennis will not work as string cannot convert to int directly. You can do something like this.
public static void main(String []args){
String s = "114 214 219";
String [] courseNumbers = s.split(" ");
Integer [] intArray = new Integer[courseNumbers.length];
for(int i= 0; i < courseNumbers.length; i++){
intArray[i] = Integer.parseInt(courseNumbers[i]);
}
}

Related

How can i print my array using Arrays.toString(reverse) without[]

how can i print the result without brackets
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int[] reverse =new int[n];
for (int i = 0; i < reverse.length; i++) {
reverse[i]=arr[arr.length-1-i];
}
in.close();
}
}
In java8, you can conveniently do any kind of String output using join, there you will have to do some manual reversing though:
String output = String.join(", ", arr);
You can't change the implementation of Arrays.toString() so you can't print your array like that.
Although, you can assign it to an string variable and then manipulate that string as you desire.
String str = Arrays.toString(reverse);
str = str.substring(1, str.length() - 1);

Input from the console in java

I know this is a basic question but I have been trying hard to find Which method I can use if I have to take 2 {123,456} as the input from console where 2 is the number of inputs to the array and {123,456} are inputs to the array. Should I be using Regex for this since it has { symbols or can it be done by scanner alone??
You can read the array part as String and then strip the curly braces using substring. Convert the String to int and store into an array.
import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int count = read.nextInt();
String arrayLine = read.next();
int array[] = new int[count];
String elements[] = arrayLine.split(",");
elements[0] = elements[0].substring(1);
elements[count-1] = elements[count-1].substring(0, elements[count-1].length()-1);
for (int i=0; i<count; i++) {
array[i] = Integer.parseInt(elements[i]);
}
for (int i : array) {
System.out.println(i);
}
}
}
Input :
2 {123,456}
Output :
123
456
Assuming you have read the input as a string, you can do the following:
String[] inputs = input.split(" ");
int arrayLength = Integer.parseInt(inputs[0]);
String inputStringData = inputs[1].substring(1, inputs[1].length());
String[] arrayElements = inputStringData.split(",");
int[] array = new int[arrayLength];
for(int i=0; i<array.length; i++) {
array[i] = Integer.parseInt(arrayElements[i]);
}

how to convert an integer string separated by space into an array in JAVA

Suppose I have a string "1 23 40 187 298". This string only contains integers and spaces. How can I convert this string to an integer array, which is [1,23,40,187,298].
this is how I tried
public static void main(String[] args) {
String numbers = "12 1 890 65";
String temp = new String();
int[] ary = new int[4];
int j=0;
for (int i=0;i<numbers.length();i++)
{
if (numbers.charAt(i)!=' ')
temp+=numbers.charAt(i);
if (numbers.charAt(i)==' '){
ary[j]=Integer.parseInt(temp);
j++;
}
}
}
but it doesn't work, please offer some help. Thank you!
You are forgetting about
resetting temp to empty string after you parse it to create place for new digits
that at the end of your string will be no space, so
if (numbers.charAt(i) == ' ') {
ary[j] = Integer.parseInt(temp);
j++;
}
will not be invoked, which means you need invoke
ary[j] = Integer.parseInt(temp);
once again after your loop
But simpler way would be just using split(" ") to create temporary array of tokens and then parse each token to int like
String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];
int i = 0;
for (String token : tokens){
ary[i++] = Integer.parseInt(token);
}
which can also be shortened with streams added in Java 8:
String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
.mapToInt(token -> Integer.parseInt(token))
.toArray();
Other approach could be using Scanner and its nextInt() method to return all integers from your input. With assumption that you already know the size of needed array you can simply use
String numbers = "12 1 890 65";
int[] ary = new int[4];
int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
ary[i++] = sc.nextInt();
}
For java 8+ you can use this way:
final Integer[] ints = Arrays.stream(numbers.split(" "))
.map(Integer::parseInt)
.toArray(Integer[]::new);
or, if you need primitive ints, you can use this:
final int[] ints = Arrays.stream(numbers.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
Reset the tmp String to "" after you parse the integer unless you wish to continue to append all the numbers of the String together. There are also alternatives as well - for instance splitting the String into an array on the space characeter, and then parsing the numbers individually
Try this out,
public static void main(String[] args) {
String numbers = "12 1 890 65";
String[] parts = numbers.split(" ");
int[] ary = new int[4];
int element1 = Integer.parseInt(parts[0]);
int element2 = Integer.parseInt(parts[1]);
int element3 = Integer.parseInt(parts[2]);
int element4 = Integer.parseInt(parts[3]);
ary[0] = element1;
ary[1] = element2;
ary[2] = element3;
ary[3] = element4;
for(int i=0; i<4; i++){
System.out.println(ary[i]);
}
}
I met similar question in android development. I want to convert a long string into two array -String array xtokens and int array ytokens.
String result = "201 5 202 8 203 53 204 8";
String[] tokens = result.split(" ");
String[] xtokens = new String[tokens.length/2 + 1];
int[] ytokens = new int[tokens.length/2 + 1];
for(int i = 0, xplace = 0, yplace = 0; i<tokens.length; i++){
String temptoken = new String(tokens[i]);
if(i % 2 == 0){
xtokens[xplace++] = temptoken;
}else {
ytokens[yplace++] = Integer.parseInt(temptoken);
}
}
You can first convert this string into an string array separated by space, then convert it to int array.

adding arrays into a multidimensional array without removing the initial value in java

Ok, say I have the code:
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
String[] ss = str.split(" ");
int[] zz = new int[ss.length];
for (int i = 0; i < ss.length; i++)
zz[i] = Integer.parseInt(ss[i]);
int[][] arr = {
zz
};
And I want to add zz every time into arr without removing the previous value. How would I go by on doing this?
ArrayList<int[]> arrayList = new ArrayList<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
String[] ss = str.split(" ");
int[] zz = new int[ss.length];
for (int i = 0; i < ss.length; i++)
zz[i] = Integer.parseInt(ss[i]);
arrayList.add(zz);
}
int[][] arr = arrayList.toArray(new int[0][0]);
There is an excellent example of how to implement your own two-dimensional ArrayList and (re-) use it in your specific case:
How to create a Multidimensional ArrayList in Java?
No need to reinvent the wheel, go for it!
Create a global-ish variable int[][] arr before the for loop, then
Put arr[][] = {} into the for loop:
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
String[] ss = str.split(" ");
int[] zz = new int[ss.length];
int[][] arr = new int[ss.length][ss.length];
for (int i = 0; i < ss.length; i++){
zz[i] = Integer.parseInt(ss[i]);
arr[i] = {
zz
};
you are putting zz into the arr array of index "i", so the values would be put in once every loop.
Hope this helps, Classic.

Convert String to int array in java

I have one string:
String arr = "[1,2]";
ie "[1,2]" is like a single String.
How do I convert this arr to int array in java?
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
};
}
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).
final String[] strings = {"1", "2"};
final int[] ints = new int[strings.length];
for (int i=0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:
String arr = "[1,2]";
JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");
int[] outArr = new int[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
outArr[i] = jsonArray.getInt(i);
}
Saul's answer can be better implemented splitting the string like this:
string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");
try this one, it might be helpful for you
String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
You can do it easily by using StringTokenizer class defined in java.util package.
void main()
{
int i=0;
int n[]=new int[2];//for integer array of numbers
String st="[1,2]";
StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
String s[]=new String[2];//for String array of numbers
while(stk.hasMoreTokens())
{
s[i]=stk.nextToken();
n[i]=Integer.parseInt(s[i]);//Converting into Integer
i++;
}
for(i=0;i<2;i++)
System.out.println("number["+i+"]="+n[i]);
}
Output :-number[0]=1
number[1]=2
String str = "1,2,3,4,5,6,7,8,9,0";
String items[] = str.split(",");
int ent[] = new int[items.length];
for(i=0;i<items.length;i++){
try{
ent[i] = Integer.parseInt(items[i]);
System.out.println("#"+i+": "+ent[i]);//Para probar
}catch(NumberFormatException e){
//Error
}
}
If you prefer an Integer[] instead array of an int[] array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.
The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.
public static void readToArray(String line, int[] resultArray) {
int index = 0;
int number = 0;
for (int i = 0, n = line.length(); i < n; i++) {
char c = line.charAt(i);
if (c == ',') {
resultArray[index] = number;
index++;
number = 0;
}
else if (Character.isDigit(c)) {
int digit = Character.getNumericValue(c);
number = number * 10 + digit;
}
}
if (index < resultArray.length) {
resultArray[index] = number;
}
}
public static int[] toArray(String line) {
int[] result = new int[countOccurrences(line, ',') + 1];
readToArray(line, result);
return result;
}
public static int countOccurrences(String haystack, char needle) {
int count = 0;
for (int i=0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle) {
count++;
}
}
return count;
}
countOccurrences implementation was shamelessly stolen from John Skeet
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

Categories