How to concatenate int and string - java

I am trying to combine two arrays in Java, one with strings and another with integers:
int [] intArray = {1, 2, 3};
String [] strArray = {"Hello", "World"};
I am trying to get two results like following:
Object [] combinedObjects = {1, 2, 3, "Hello", "World"};
String [] combinedStrings = {"1", "2", "3", "Hello", "World"};

Edit: your question was changed after I posted my answer and it seems a more fitting answer has been posted, Instead of deleting my
post i'm going to leave the last bit here in case you need to do any
conversion from your joined array later in your project.
You also have the option to parse your data (this may be useful to you if you ever want to get the int's back from your array.
int tempInt = Integer.parseInt(tempString);
or alternatively:
String tempString = String.valueOf(tempArray[i]);
A good reference for changing types can be found at javadevnotes

you have two approachs :
1 - using arrayList:
ArrayList a = new ArrayList();
for(int i = 0 ; i < intArray.length ; i++)
a.add(intArray[i]);
for(int i = 0 ; i < strArray.length ; i++)
a.add(strArray[i]);
now you have answer in ArrayList
2 - use String.valueof() method :
String combinedStrings[] = new String[strArray.length+intArray.length];
int index= 0;
for(int i = 0 ; i < strArray.length ; i++)
combinedStrings[index++] = strArray[i];
for(int i = 0 ; i < intArray.length ; i++)
combinedStrings[index++] = String.valueOf(intArray[i]);
now you have answer in combinedStrings array

If you are not stucked to very old java version there is seldom a good reason to use Array. Especially if you want to operate on the array, enlarge or reduce it. The java collection framework is far flexibler. Since java8 the introduction of streams on collections offers a wide range of operations in a very compact coding.
Using streams I would solve your problem as following:
Object [] combinedObjects = Stream.concat(
Arrays.stream( intArray).boxed(),
Arrays.stream( strArray))
.toArray(Object[]::new);
String [] combinedStrings = Stream.concat(
Arrays.stream( intArray).mapToObj( i -> "" + i),
Arrays.stream( strArray))
.toArray(String[]::new);
If your input and your desired output should be a Collection then the code would appear even a little shorter:
Collection<Object> combined = Stream.concat(
intCollection.stream(),
strCollection.stream())
.collect( Collectors.toList() );

You should to convert the Integer values to String to solve your problem, because the Array can have one type of information :
public static void main(String args[]) {
int[] intArray = {1, 2, 3};
String[] strArray = {"Hello", "World"};
String[] combinedStrings = new String[intArray.length + strArray.length];
int i = 0;
while (i < intArray.length) {
//convert int to string with adding an empty string
combinedStrings[i] = intArray[i] + "";
i++;
}
int j = 0;
while (j < strArray.length) {
combinedStrings[i] = strArray[j];
i++;
j++;
}
for (String val : combinedStrings) {
System.out.println(val);
}
}
You can learn more about arrays in Oracle tutorial, part Creating, Initializing, and Accessing an Array

Related

convert List<List<Integer>> to 2D char array?

I have a List<List<Integer>> arr which is 2D_INTEGER_ARRAY. I need to convert this to 2D char[][] array. I tried with below code but it is giving compilation issue which is obvious but not able to figure out how can I do that?
public static int largestMatrix(List<List<Integer>> arr) {
char[][] matrix = new char[arr.size()][];
for (int i = 0; i < arr.size(); i++) {
List<Integer> row = arr.get(i);
// below line is giving error
matrix[i] = row.toArray(new char[row.size()]);
}
}
Error is:
[Java] The method toArray(T[]) in the type List<Integer> is not applicable for the arguments (char[])
Integer and char are separate types. If you want an integer represented as a digit, you need to convert it (casting will only give you the ASCII representation). Besides, you can't call toArray() with a primitive array. You'll have to iterate and convert manually:
matrix[i] = new char[row.size()];
for (int j = 0; j < row.size(); j++) {
matrix[i][j] = Character.forDigit(row.get(j), 10);
}
Basically you are trying to convert List<Integer> to char[] in this line:
matrix[i] = row.toArray(new char[row.size()]);
You can do so using this:
matrix[i] = row.stream()
.map(j -> Integer.toString(j))
.collect(Collectors.joining())
.toCharArray();
We can do it purely using java-8 streams as follows, I have taken a cue from Kartik's answer on the conversion of Stream of Integer to Stream of char[]:
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6), Arrays.asList(7,8,9));
char[][] chars = list.stream().map(l -> l.stream()
.map( i-> Integer.toString(i))
.collect(Collectors.joining())
.toCharArray())
.toArray(char[][]::new);

Split Numbers String to Integer Array

String contains an unknown length of numbers which are seperated by "-", for example:
string = "4-12-103-250-302"
I need these numbers in an integer array like this:
intArray[] = { 4, 12, 103, 250, 302 }
Can you give me a code example/solution?
You can use the String.Split method in Java.
Then convert the Array to an Integer Array.
string str = "4-12-103-250-302";
String[] parts = string.split("-");
int[] intArray = new int[parts.length];
for(int i = 0; i < parts.length -1; i++)
{
intArray[i] = Integer.parseInt(parts[i]);
}
Then you can just access all of the parts just as an array would work.
intArray[0]
intArray[1]
.
.
etc
You want to split the string into an array by a character delimiter. Then you want to apply a function to each item in the array to make it into an integer.
In php:
<?php
$string = "4-12-103-250-302";
$aray = $string.split("-");
array_walk($aray, 'intval');
Other languages will have similar constructs.
Since Java < 8 doesn't have use lambdas, try this:
str = "4-12-103-250-302";
String[] straray = str.split("\\-", -1);
int[] intArray = new int[straray.length];
for (int i=0; i < straray.length; i++) {
intArray[i] = Integer.parseInt(straray[i]);
}

How to turn an array of Strings into an Array of Ints?

I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
What I want this method to do is take an input array: ["1","2","3"] with each item being a string
and return [1,2,3] where each item is an int.
I'm calling the method with this code
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
In this case, toBeSorted is both being declared here and initialized at the same time.
Whenever I try to run this I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)
Java Result: 1
Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.
The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.
So I guess what I'm asking is
1) why does my code not work?
and
2) is there an easier way to take an input from the user and turn it into an array of ints than this?
For those who would like to see my entire code, here it is
The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered
package sorter;
import java.util.Scanner;
import java.util.Arrays;
public class Sorter {
public static void main(String[] args) {
Scanner userInput = new Scanner( System.in );
System.out.println("Enter a list to be sorted, seperate numbers by commas:");
String input = userInput.nextLine(); //Gets aan input as a String
String delims = "[,]+"; //Use Comma as Delimiter
String[] inputStringArray = input.split(delims); //Parse String and creates
//an array
System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
//the given array
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
int test = toBeSorted[0] + toBeSorted[1];
System.out.println(test);
}
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
}
You got the range of the loop wrong :
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The valid indices of the array are between 0 and arrayString.length - 1.
As a bonus, here's a nicer way to achieve the same with Java 8:
public static int[] ArrayStringToArrayInt(String[] arrayString)
{
return Stream.of(arrayString).mapToInt(Integer::parseInt).toArray();
}
Off-by-one error here:
for (int i = 0; i <= arrayString.length; i++ ) {
^
It should be:
for (int i = 0; i < arrayString.length; i++ ) {
This is wrong
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The indexes of the array are between the 0 and length -1
Variable i should go from 0 to N-1, N being the length of the array. Java arrays, like C ones are zero-based, which means that you should iterate them from 0 to N-1. So your for should look like this:
for (int i = 0; i < arrayString.length; i++)
You could use a stream:
Arrays.stream(arrayString).mapToInt(Integer::parseInt).toArray()
Simply change this statement
for (int i = 0; i <= arrayString.length; i++ )
To
for (int i = 0; i < arrayString.length; i++ )
It will work fine. ArrayIndexOutOfBoundsException means you're trying to access an index in the array that does not exist.
For example,
int [] a= new int [5];
Then the indices available to me are
a [0], a [1], a [2], a [3], and a [4]
I cannot access
a [5]
And if i try i would get ArrayIndexOutOfBoundsException.
That means array indices start at 0 and go upto array length-1.
Hope this helps.

Java - Split a string to an array

I have a number that is submitted by the user.
I want to make something like this: 1568301
to an array like this: 1, 5, 6, 8, 3, 0, 1.
How can I do this without adding "," between every digit or something like that? (type int).
Thanks.
String str = "123456";
str.toCharArray();
will do roughly what you want. A more complex version using a regular expression is:
String str = "123456";
str.split("(?<!^)");
which uses a negative lookbehind (split() takes a regexp - the above says split on anything provided the element to the left isn't the start-of-line. split("") would give you a leading blank string).
The second solution is more complex but gives you an array of Strings. Note also that it'll give you a one-element empty array for a blank input. The first solution gives you an array of Chars. Either way you'll have to map these to Integers (perhaps using Integer.parseInt() or Character.digit()?)
"1568301".toCharArray() should do the job.
You can use the Split with ""
It'll be like this:
String test = "123456";
String test2[] = test.split("");
for (int i = 1; i < test2.length; i++) {
System.out.println(test2[i]);
}
If your number is in String format, you can simply do this:
String str = "1568301";
char[] digitChars = str.toCharArray();
Are expecting something like this
String ss ="1568301";
char[] chars = ss.toCharArray();
cant you simply populate the array by iterating over the String ??
char[] arr = new char[str.length];
for(int i=0; i<str.length; i++){
arr[i] = str.charAt(i);
}
or even better
char[] arr = "0123456".toCharArray();
To get the values in an array of integers:
String str = "1568301";
int[] vals = new int[str.length];
for (int i = 0; i < str.length(); i++) {
vals[i] = Character.digit(str.charAt(i), /* base */ 10));
}
The second parameter of Character.digit(char, int) is the number base. I'm assuming your number is base 10.
I guess you are looking at to have an array of int.
I would suggest to have the following code :
String str = "1568301";
int [] arr = new int[str.length()];
for(int i=0; i<arr.length; i++)
{
arr[i] = str.charAt(i)-'0';
}

char array to int array

I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!

Categories