char array to int array - java

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!

Related

Integers in array Java

I have an array that contains [45,8,50,15,65,109,2]. i would like to check to see if the zero element of my array is greater than my first element.
if ( 45 > 8)
then i would like to add 45 to brand new sub array.
i would like to continue checking my array for anything that is bigger than 45 and add it to the new sub array.
The new sub array has to keep the numbers added in the way they where added.The result should be [45,50,65,109]
I thought by creating this was going in the right direction but im doing something wrong so please help.
int[] x = [45,8,50,15,65,109,2];
int[] sub = null;
for(int i = 0; i > x.length; i++) {
for(int k = 0; k > x.length; k++) {
if(x[i] > x[k]){
sub = i;
First thing first. Your question contains some errors.
you should write int[] x = {45,8,50,15,65,109,2}; instead of int[] x = [45,8,50,15,65,109,2]; You can not use [] to initialize array!
What does it mean for(int i = 0; i > x.length; i++). Your program must not run! Because, the value of i is less than x.langth. First condition check is false, so loop will not works!
Same for for(int k = 0; k > x.length; k++)
How do you want to store value in an array without index? You have to write sub[i] = x[i]; here, i means what index value you want to store where!
Finally, do you want to do sorting? If yes, then you need another variable named temp means temporary!
Try to clear the basic and after then try this code.Sorting Link
Best of Luck!
It is possible to filter the input array using Java 8 Stream API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x)
.filter(n -> n >= x[0])
.toArray();
System.out.println(Arrays.toString(sub));
Output:
[45, 50, 65, 109]
If you're trying to fetch everything greater than 0th element.
Use the following:
Plain old java code:
int[] x = {45,8,50,15,65,109,2};
int[] sub = new int[x.length];
int first = x[0];
sub[0]=first;
int index=1;
for(int i = 1; i < x.length; i++) {
if(x[i] > first){
sub[index]=x[i];
index++;
}}
Streams API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x).filter(number -> number>=
x[0]).toArray();
where stream() is converting array to a stream, filter is applying the required condition and then ending it with conversion into an Array again.

char[i] returns wrong number

I have an "algorithm" which has an integer k as input parameter. For example, I pass k = 54321 as argument. In this method I want:
Convert this integer to char array, so that instead of 54321 it would be [5,4,3,2,1] and so on
Sort this array ascending, add each char to ArrayList
return ArrayList
But when it comes to for loop, if I get item by char[position] it gives me random value. More practically,
public class Main {
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(chars[i]);
}
return tab_cyfr;
}
}
This should return me following [1,2,3,4,5] but returns [49, 50, 51, 52, 53], where those numbers came from?
Plus sorry for variables naming, I'm practicing random exercises on local variables.
String.valueOf(k).toCharArray() returns the characters in the String as their char representation. As per ASCII table 49 is the char value of 1, 50 of 2, and so on.
You should convert k to digits, not to chars. This can be done by using % operation:
int k = 8421753;
ArrayList<Integer> digits = new ArrayList<>();
while (k > 0) {
digits.add(k % 10);
k /= 10;
}
Collections.sort(digits);
System.out.println(digits); // [1, 2, 3, 4, 5, 7, 8]
The ASCII Problem
It gets converted to a string, so the numbers are stored as ASCII values in the char array.
The problem is this line:
char[] chars = String.valueOf(k).toCharArray();
If you were to look up the ASCII values of the digits 1,2,3,4,5, you would see they are equal to 49, 50, 51, 52, 53,respectively.
How to Solve the Issue
To fix this issue, run a loop through the int number, take it apart digit by digit, and store them as ints, not chars, and then just sort your int[].
Replacing your ArrayList<Integer> to ArrayList<Character> solve this problem because it store characters '1', '2', etc not their Integer values which are 49, 50...
So below code return what you expect: [1, 2, 3, 4, 5]
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Character> sortMet(int k) {
ArrayList<Character> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(chars[i]);
}
return tab_cyfr;
}
These numbers are ASCII codes of characters in the array. For example, 48 for character 0, 49 for character 1, and so forth.
It seems that you are using an array list of Integers, so the list elements will print like standard int and long integers. To fix the issue, replace ArrayList<Integer> with ArrayList<Character>.
This line does not compile:
tab_cyfr.add(chars[i]);
so it is strange that you get [49, 50, 51, 52, 53].
Even if it compiled it would add the ascii value of chars[i],
but you want its numeric value.
One way to get it is:
tab_cyfr.add(Integer.parseInt("" + chars[i]));
toCharArray() method returns the character array and when you sort array is sorted by its ASCII value. So those random numbers are ASCII values.
To convert char into Integer:-
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
for (int i = 0; i < n; i++) {
tab_cyfr.add(Character.getNumericValue(chars[i]));
}
Collections.sort(tab_cyfr);
return tab_cyfr;
}
This code should work instead.
public static void main(String[] args) {
System.out.println(sortMet(54321));
}
static ArrayList<Integer> sortMet(int k) {
ArrayList<Integer> tab_cyfr = new ArrayList<>();
char[] chars = String.valueOf(k).toCharArray();
int n = chars.length;
Arrays.sort(chars);
for (int i = 0; i < n; i++) {
tab_cyfr.add(Character.getNumericValue(chars[i]));
}
return tab_cyfr;
}
Character.getNumericValue(chars[i]) ensures that you push the actual char value into tab_cyfr and not the ASCII value of it.

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

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

Categories