Split Numbers String to Integer Array - java

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]);
}

Related

How to concatenate int and string

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

How to tokenize from a String of numbers to an int array

I have a String of this kind
String s=1956;
and want to convert this String in int[] array
[1,9,5,6];
Any suggestion?
I would do it like this:
int[] digits = new int[s.length()];
for (int i = 0; i < digits.length; ++i) {
digits[i] = s.charAt(i)-'0';
}
I could never bring myself to use Integer.parseInt(String) just to translate a digit character into an integer.
You can use the split method of String to convert it to a String[], and then you can iterate over it calling Integer.parseInt to populate a int[]
One option would be
char[] nums = s.toCharArray();
int[] parsed = new int[nums.length];
for (int i = 0; i < nums.length; ++i){
parsed[i] = Integer.parseInt(String.valueOf(nums[i]));
}
I'm going to provide a the most possible simple solution to this;
String s = "1956";
int array[] = new int[4];
array[0] = Integer.parseInt(s.charAt(0)+"");
array[1] = Integer.parseInt(s.charAt(1)+"");
array[2] = Integer.parseInt(s.charAt(2)+"");
array[3] = Integer.parseInt(s.charAt(3)+"");
Obviously loops can do this, but you really didn't tell us the context of your situation

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';
}

Convert an integer to an array of characters : java

What is the best way to convert an integer into a character array?
Input: 1234
Output: {1,2,3,4}
Keeping in mind the vastness of Java language what will be the best and most efficient way of doing it?
int i = 1234;
char[] chars = ("" + i).toCharArray();
You could try something like:
String.valueOf(1234).toCharArray();
Try this...
int value = 1234;
char [] chars = String.valueOf(value).toCharArray();
You can convert that integer to string and then convert that string to char arary:-
int i = 1234;
String s = Integer.toString(i);
Char ch[] = s.toCharArray();
/*ch[0]=1,ch[1]=2,ch[2]=3,ch[3]=4*/
This will convert an int to a 2 char array. If you are trying to get the minimum amount of chars, try this.
//convert int to char array
int valIn = 111112222;
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.putInt(valIn);
char [] charArr = new char[4];
charArr[0] = bb1.getChar(0);
charArr[1] = bb1.getChar(2);
//convert char array to int
ByteBuffer bb2 = ByteBuffer.allocate(8);
bb2.putChar(0,charArr[0]);
bb2.putChar(2,charArr[1]);
long valOut = bb2.getInt(0);
I was asked this question in google interview. If asked in interviews use module and division. Here is the answer
List<Integer> digits = new ArrayList<>();
//main logic using devide and module
for (; num != 0; num /= 10)
digits.add(num % 10);
//declare an array
int[] arr = new int[digits.size()];
//fill in the array
for(int i = 0; i < digits.size(); i++) {
arr[i] = digits.get(i);
}
//reverse it.
ArrayUtils.reverse(arr);
Say that you have an array of ints and another method that converts those ints to letters, like for a program changing number grades to letter grades, you would do...
public char[] allGradesToLetters()
{
char[] array = new char[grades.length];
for(int i = 0; i < grades.length; i++)
{
array[i] = getLetter(grades[i]);
}
return array;
}

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