String[] with ints. how to get them out java - java

I have a String[] with numbers like {"12", "3", "5"}.
I want to put these numbers in a int[], like {12, 3, 5}.
How can I do this?

for loop is your friend here.
It will be done using a for loop and string to integer conversion by Integer.parseInt(str).
I will not give any code here but as an algorithm, it will be:
1. Loop over string array.
2. For each string do
a. Convert string to integer
b. store it in integer array

You could write a method that will do the conversion using the parseInt method on each element:
public int[] convert(String[] stringArray) throws NumberFormatException {
if (stringArray == null) {
return null;
}
int intArray[] = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArray[i] = Integer.parseInt(stringArray[i]);
}
return intArray;
}

Related

Casting string to integer array [duplicate]

//convert the comma separated numeric string into the array of int.
public class HelloWorld
{
public static void main(String[] args)
{
// line is the input which have the comma separated number
String line = "1,2,3,1,2,2,1,2,3,";
// 1 > split
String[] inputNumber = line.split(",");
// 1.1 > declare int array
int number []= new int[10];
// 2 > convert the String into int and save it in int array.
for(int i=0; i<inputNumber.length;i++){
number[i]=Integer.parseInt(inputNumber[i]);
}
}
}
Is it their any better solution of doing it. please suggest or it is the only best solution of doing it.
My main aim of this question is to find the best solution.
Java 8 streams offer a nice and clean solution:
String line = "1,2,3,1,2,2,1,2,3,";
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
Edit: Since you asked for Java 7 - what you do is already pretty good, I changed just one detail. You should initialize the array with inputNumber.length so your code does not break if the input String changes.
Edit2: I also changed the naming a bit to make the code clearer.
String line = "1,2,3,1,2,2,1,2,3,";
String[] tokens = line.split(",");
int[] numbers = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
numbers[i] = Integer.parseInt(tokens[i]);
}
By doing it in Java 7, you can get the String array first, then convert it to int array:
String[] tokens = line.split(",");
int[] nums = new int[tokens.length];
for(int x=0; x<tokens.length; x++)
nums[x] = Integer.parseInt(tokens[x]);
Since you don't like Java 8, here is the Best™ solution using some Guava utilities:
int[] numbers = Ints.toArray(
Lists.transform(
Splitter.on(',')
.omitEmptyStrings()
.splitToList("1,2,3,1,2,2,1,2,3,"),
Ints.stringConverter()));

How to Convert an String array to an Int array?

I have made research for a couple hours trying to figure out how to convert a String array to a Int array but no luck.
I am making a program where you can encrypt a message by using three rotors. I am able to type a message and get the index number for the first rotor (inner rotor) to encrypt into the third rotor (outer rotor). The problem is the index number is in a string array which I want it to become a int array.
Yes, I have tried
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
or any form of that. I'm not unsure if I have java 8 since it doesn't work, but it gives me an error.
Can someone help me how to convert a String array to a Int array?
public void outerRotorEncrypt() {
String[] indexNumberSpilt = indexNumber.split(" ");
System.out.println("indexNumber length: " + indexNumber.length()); //test
System.out.println("indexNumberSpilt length: " + indexNumberSpilt.length); //test
System.out.println("Index Number Spilt: " + indexNumberSpilt[3]); //test
System.out.println("");
System.out.println("");
System.out.println("testing from outerRotorEncrypt");
System.out.println("");
for(int i = 1; i < indexNumberSpilt.length; i++){
secretMessage = secretMessage + defaultOuterRotorCharacterArray[indexNumberSpilt[i]];
}
System.out.println("Secret Message from outerRotorEncrypt: " + secretMessage);
}
If you are using Java8 than this is simple way to solve this issue.
List<?> list = Arrays.asList(indexNumber.split(" "));
list = list.stream().mapToInt(n -> Integer.parseInt((String) n)).boxed().collect(Collectors.toList());
In first Line you are taking a generic List Object and convert your array into list and than using stream api same list will be filled with equivalent Integer value.
static int[] parseIntArray(String[] arr) {
return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}
So take a Stream of the String[]. Use mapToInt to call Integer.parseInt for each element and convert to an int. Then simply call toArray on the resultant IntStream to return the array.
Have you tried:
int[] array = new int[indexNumberSpilt.lenght()];
for ( int i=0;i<indexNumberSpilt.lenght();i++ ){
array[i] = Integer.valueOf(indexNumberSpilt[i]);
}
int[] array == Arrays.asList(strings).stream()
.mapToInt(Integer::parseInt).toArray();
The reason why it's giving an error is because of ==, changing that to = (assignment operator) should work, e.g.:
String[] input = new String[]{"1", "2"};
int[] array = Arrays.asList(input).stream()
.mapToInt(Integer::parseInt).toArray();
for(int a : array){
System.out.println(a);
}
Small Demo
String[] string = { "0", "1", "11", "0", "0", "1", "11", "0", "0", "1",
"11", "0" };
List<String> temp = Arrays.asList(string);
List<Integer> temp1 = new ArrayList<Integer>();
for (String s : temp) {
temp1.add(Integer.parseInt(s));
}
int[] ret = new int[temp1.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = temp1.get(i).intValue();
}
System.out.println(Arrays.toString(ret));
}
int[]
If you want an int[] array:
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
int[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(result));
Integer[]
String indexNumber = "1 2 3 4";
String[] indexNumberSpilt = indexNumber.split(" ");
Integer[] result = Stream.of(indexNumberSpilt).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(result));
Both examples will print:
[1, 2, 3, 4]

How do I grab the numbers in a String array and place them into an int array

I have a String array that contains {127,a,0,10}. I want to grab the numbers in that array and place them into an int array that will now contain {127,0,10}.
I tried to use parseInt on each individual value in the String array but it does not worked on characters in a string.
Thank you!
The Java 8 answer:
int[] results = Arrays.stream(arr)
.filter(s -> s.matches("-?[0-9]+"))
.mapToInt(s -> Integer.parseInt(s))
.toArray();
EDIT: Even better:
int[] results = Arrays.stream(arr)
.filter(s -> s.matches("-?[0-9]+"))
.mapToInt(Integer::parseInt)
.toArray();
demonstrating yet another new cool language feature. I should have seen this the first time. It's pathetic that I haven't yet mastered Java 8 despite its being officially available for a whole two weeks now.
Validate int value
You could create a function that would tell you if a string represents valid int value as so:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
Source: Determine if a String is an Integer in Java
Remove unwanted elements
You can now easily loop on the array and remove unwanted elements as so:
for(int i=0; i< myStringArray.length(); i++){
if(!isInteger(myStringArray[i])){
myStringArray[i]=null;
}
}
I tried to use parseInt on each individual value in the String array
but it does not worked on characters in a string.
parseInt does not work for characters, that is by design of that API. It will throw an exception in case of invalid numeric value. So what you have to do is encapsulate your code in try/catch. And in case of NumberFormatException don't put the item in second array, otherwise add. Hope you will be able to code this.
Try something like this
Integer[] numberArray = new Integer[stringArray.length];
int index = 0;
for(String s : stringArray) {
try {
Integer stringAsNumber = Interger.valueOf(s);
numberArray[index] = stringAsNumber;
index++;
} catch(NumberFormatException nfe) {
//String is not a valid number
}
}
return numberArray;
You can use a regex to determine if a string can be parsed into an Integer.
String [] arr = {"1233", "45", "a34", "/", "0", "19"};
for(int i = 0; i < arr.length; i++)
if(arr[i].matches("-?[0-9]+"))
System.out.println(arr[i]);
The rest is easy to do.
EDIT: This detects both positive and negative numbers.
try this..
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String[] var = new String[]{"127","a","0","10"};
List<Integer> var2 = new ArrayList<Integer>();
//Integer extraction
for (String s : var)
{
try{
var2.add(Integer.parseInt(s));
System.out.println(Integer.parseInt(s));
}catch(NumberFormatException e){}
}
//int array if you want array only or you just use List<Integer>
int[] array = new int[var2.size()];
for(int i = 0; i < var2.size(); i++) array[i] = var2.get(i);
}
}

Is there a way of traversing from string to int array and vice versa

In Java, given the array
int a[] = {1,2,3}
I can do Arrays.toString(a) to get
"[1,2,3]"
Is there an equally convenient way to return this String back to its antecedent array?
Or must I go through the whole split, for-loop, parseInt stuff?
UPDATE
Thanks everyone for all the thoughts. I rolled out my own function as
String src[] = data.split("\\D+");//data is intArrayAsString: [1,2,3]
int[] nums = new int[src.length - 1];
int ndx = 0;
for (String s : src) {
try {
nums[ndx] = Integer.parseInt(s);
ndx++;
} catch (NumberFormatException e) {
}
}
return nums;
Note: the word traverse seems to have thrown a few people off. By "traversing" I meant the ability to move back and forth from the string to the int array.
As far as i know, no.
But it's easy to do using Split.
I just did this, if you don't understand how to do it:
int[] arr = {1, 2, 3, 4};
String toString = Arrays.toString(arr);
System.out.println(toString);
// we know it starts with [ and ] so we skip it
String[] items = toString.substring(1, toString.length() - 1).split(",");
int[] arr2 = new int[items.length];
for (int i = 0; i < items.length; ++i)
{
arr2[i] = Integer.parseInt(items[i].trim()); // .trim() because it adds the space and parseInt don't like spaces
}
System.out.println(Arrays.toString(arr2));
(free to improve it, it's just a draft)
I don't know of any existing method, so I wrote you my own version:
import java.util.Arrays;
public class ArrayToString {
public static void main(String[] args) {
int a[] = {1,2,3};
String serialized = Arrays.toString(a);
System.out.println(serialized);
int[] b = stringToIntArray(serialized);
System.out.println(Arrays.toString(b));
}
private static int[] stringToIntArray(String serialized) {
// remove '[' and ']'
String raw = serialized.replaceAll("^\\[(.*)\\]$", "$1");
// split by separators
String[] splitStrings = raw.split(", ");
// create new int array
int[] b = new int[splitStrings.length];
for (int i = 0; i < splitStrings.length; i++) {
String splitString = splitStrings[i];
// parse each text individually
b[i] = Integer.parseInt(splitString);
}
return b;
}
}

Converting a String array into an int Array in java

I am new to java programming. My question is this I have a String array but when I am trying to convert it to an int array I keep getting
java.lang.NumberFormatException
My code is
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
intarray[i]=Integer.parseInt(str);//Exception in this line
i++;
}
}
Any help would be great thanks!!!
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
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Since you are trying to get an Integer[] array you could use:
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
Your code:
private void processLine(String[] strings) {
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}
Note, that this only works for Java 8 and higher.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number
separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
public static int[] strArrayToIntArray(String[] a){
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
return b;
}
This is a simple function, that should help you.
You can use him like this:
int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}

Categories

Resources