Convert an integer to an array of characters : java - 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;
}

Related

Converting selective elements in an array of Strings to their ascii values in java

I'm working on a project currently where I have a String array of 8 values that number but are stored as strings. String[3] and String[7] are letters stored as strings that I need to convert to their ASCII values, but I can't seem to do that in java. I keep getting an error saying that I cannot convert a String type to int type, and I don't know any other way to get these string letters to their ASCII values. Here is the code I have so far...
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = Integer.parseInt(stringInfo[x]);
System.out.println(info[x]);
x++;
}
so within that array, those two values need to be turned into ASCII but that code keeps getting errors and I don't know how to fix it. How would I do this?
The best way to do this would be to first convert your string to a character, and then cast your character as an int. I know this sounds like a lot, but it is actually only one line of code.
int ascii = (int) mystring.charAt(0);
The reason this works is that characters (char) are a primary type in Java, and they essentially are just bit, which is why you can actually compare chars to each other using == rather than .equals.
This is a function that use ascii code to convert string of unsigned number to an integer:
static int stringToNumber(String input) {
int output = 0;
for (int x = 0; x < input.length(); x++) {
output = output * 10 + (input.charAt(x) - '0');
}
return output;
}
And your code
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = stringToNumber(stringInfo[x]);
System.out.println(info[x]);
x++;
}
But if you don't need ascii code or your number are signed number java made it easier you can only use this method to convert string to number
Integer result = Integer.valueOf(stringInfo[x]);
And your code:
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = Integer.valueOf(stringInfo[x]);
System.out.println(info[x]);
x++;
}
You can try-
String stringInfo [] = input.split(",");
int info [] = new int [8];
int x = 0;
while (x<stringInfo.length) {
info[x] = stringInfo.charAt(x);
System.out.println(info[x]);
x++;
}
stringInfo.charAt(i) will give the Ascii value at index(i) of stringInfo

How to generate a random char array of a specific length using specific characters

I am trying to take this char array here:
char[] options = {'F','Z','P','E','N','T','L','C','D','O'};
and generate a new random char array of a specific length. Like this:
char[] results ={'Z','E','L','C'...} all the way up to a length of 70 characters long. I've already tried to create a new char such as char[] results = new char[70] and then using a for loop to try to get this. But for some reason my mind is blanking. Can anybody refresh me? Thanks all
Kind of straightforward solution
char[] options = {'F','Z','P','E','N','T','L','C','D','O'};
char[] result = new char[70];
Random r=new Random();
for(int i=0;i<result.length;i++){
result[i]=options[r.nextInt(options.length)];
}
private static char[] options = {'F','Z','P','E','N','T','L','C','D','O'};
public static char[] createRandomArray() {
Random r = new Random();
char[] arr = new char[70];
for (int i = 0; i < arr.length; i++) {
arr[i] = options[r.nextInt(options.length)];
}
return arr;
}

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 - Convert a String of letters to an int of corresponding ascii?

I want to convert a String, lets say "abc", to an int with the corresponding ascii: in this example, 979899.
I've run into two problems:
1) what I wrote only works for characters whose ascii is two characters long and
2) since these numbers get very big, I can't use longs and I'm having trouble utilizing BigIntegers.
This is what I have so far:
BigInteger mInt = BigInteger.valueOf(0L);
for (int i = 0; i<mString.length(); i++) {
mInt = mInt.add(BigInteger.valueOf(
(long)(mString.charAt(i)*Math.pow(100,(mString.length()-1-i)))));
}
Any suggestions would be great, thanks!
What's wrong with doing all the concatenation first with a StringBuilder and then creating a BigInteger out of the result? This seems to be much simpler than what you're currently doing.
String str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
you don't have to play the number game. (pow 100 etc). just get the number string, and pass to constructor.
final String s = "abc";
String v = "";
final char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
v += String.valueOf((int) chars[i]);
}
//v = "979899" now
BigInteger bigInt = new BigInteger(v); //BigInteger
BigDecimal bigDec = new BigDecimal(v); // or BigDecimal
To handle n-digit numbers, you will have to multiply by a different power of ten each time. You could do this with a loop:
BigInteger appendDigits(BigInteger total, int n) {
for (int i = n; i > 0; i /= 10)
total = total.multiply(10);
return total.plus(new BigInteger(n));
}
However, this problem really seems to be about manipulating strings. What I would probably do is simply accumulate the digits int a string, and create a BI from the String at the end:
StringBuilder result = new StringBuilder();
for (char c : mString.getBytes())
result.append(String.valueOf(c));
return new BigInteger(result.toString());

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