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

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

Related

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 do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

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