How can I convert couple of characters to int, to keep the question simple let's assume this :
char c1 = '1';
char c2 = '4';
char c3 = '5';
What would be the efficient way to get 145 type int.
int myInt = Integer.parseInt(""+c1+c2+c3);
""+c1 gives you a String containing the char c1, to which you append the characters c2 and c3. Then you use parseInt() to convert it to an integer.
A more straightforward (but less robust) method would be this:
int myInt = 100*(c1-'0') + 10*(c2-'0') + (c3-'0');
c1-'0' gives you the number represented by c1 as opposed to the character code. Then you simply shift things to the correct decimal places and add.
int myInt = (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0');
Here is a more general method to convert a char array to int:
int valueOf(char[] input){
int result = 0;
for(char c : input) {
result *= 10;
result += Character.digit(c, 10);
}
return result;
}
The most correct way to convert a single digit character to an int is Character.digit(char ch, int radix), which can handle values in bases besides 10.
Strings are ultimately backed by a char[], so you could do the following:
char c1 = '1';
char c2 = '4';
char c3 = '5';
int converted = Integer.parseInt(new String(new char[]{c1, c2, c3}));
There are probably several other perfectly good ways to do this.
Related
I have very basic question.
How is possible for int a = 'a' to give 97 in output.
Below is my code:
class myClass {
int last = 'a' ;
myClass () {
System.out.println(last );
}
}
You can have a look at this: Why are we allowed to assign char to a int in java?
Basically, you are assigning a char to your int. A char is technically an unsigned 16-bit character. That's why you can assign it to an int.
Hope this helps.
You can basically cast the char to the int and store it as int:
int a = (int)'a';
System.out.println(a); //prints 97
Since Java can do the basic castings from your type specifications, you do not need to explicity write casting even.
int a = 'a';
System.out.println(a); // prints 97
The output is the ASCII value of the character stored in last. The ASCII value of the character 'a' is 97, and hence the output on the console is 97.
you have to take 'a' as a char
char char1 = 'a';
then cast it to int
int num = (int) char1 ;
I am trying to reform a string from ascii characters. I noticed when I break down ascii it matches the number with the ascii char, this changes when I tried to do (c+=c+0) on it as seen below, I tried to revert back to the original string but it doesn't seems to work. I was wondering does the ascii number change when you append it to a string?
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0);
char d = b.charAt(0);
System.out.println(d-=d+0); //blank
When you use + to sum a char with and int, the result will be promoted
to int.
When you use compound assignment operators +=, the result will be converted to left
operand data type(in this case, char)
This is what happens with your code:
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); //'e'
System.out.println(c+0); //101 -ascii
b.append(c+=c+0); // result of c+c+0 is int 202, it is converted to char Ê
char d = b.charAt(0); // char d = Ê
System.out.println(d-=d+0); // result of d-(d+0) is int 0, it will be converted to null
It's not clear what you're trying to accomplish, but hopefully this example helps you figure out what's going on:
public static void main(String[] args) {
StringBuilder b = new StringBuilder();
char c = "e".charAt(0);
System.out.println(c); // e
System.out.println((int) c); // 101
char doubleC = (char) (c + c);
b.append(doubleC);
char d = b.charAt(0);
System.out.println((int) d); // 202
System.out.println(d - c); // 101
System.out.println((char) (d - c)); // e
}
Whether a character is printed as a letter or its ASCII value depends on its type. You can see that (int) c casts the character to its int ASCII value. Your approach of c+0 also does this but in a less intuitive way.
You also apparently want to "undo" your modification to c, but subtracting d-d always gives you 0. You need to store your value of c and subtract that from d.
+0s don't do anything because the character is underneath a number (so it's essentially like saying 101 + 0).
d-=d+0 evaluates to d = d - d + 0, so (because we're manipulating chars) d - d = 0
If you wanted to get c from d, you'd have to do d = d - c, because 'c' is the difference between the initial and the final value.
So no, the ASCII number of a character doesn't change, you're just not doing the reverse calculation as you should be.
It's like saying: x + y = z,
and then wondering why z - z != y.
You should be doing: z - x = y
#Edit
To add to your comment under pkpnd's answer - if you have only String b to work with, you'd still need to know the difference (i.e. by how much you increased/decreased the number) to reverse to the original chars.
char c = '7';
int i = c - '0';
// Here value of '0' is 48 and c = '7' is 55. Therefore, i = 55 - 48 or 7;
More example:
String s = "453467"
Here, you may need the integer value located at 3rd cell.
You can first make a char variable. Then convert the char variable into an int.
char c = s.charAt(3);
int i = c - '0';
Sometimes this thing is needed for solving programming problems and to take the input from the user as an string.
Can you tell me the other ways to convert them. This will be very helpful for me to solve problems. THANKS!!
You want:
Character.getNumericValue(char ch)
Use the Integer class:
`int yourInt = Integer.parseInt(Character.toString('0'));
I understand how to convert a single char to an int, but how can I convert a String to chars, so I can convert the chars to ints? For example, for the string hello:
chars[1] = h => 104
chars[2] = e => 101
chars[3] = l => 108
chars[4] = l => 108
chars[5] = o => 111
The output should make it easy to convert five-letter Strings to five separate integers, each representing one character, then convert them back to char and print them as a single String again.
You can try like this:
String s = "hello";
char[] data = s.toCharArray(); // returns a length 5 char array ( 'h','e','l','l','o' )
Now you can call this function to convert it into int.
int charToInt(char []data,int start,int end) throws NumberFormatException
{
int result = 0;
for (int i = start; i < end; i++)
{
int digit = (int)data[i] - (int)'0';
if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
result *= 10;
result += digit;
}
return result;
}
Using getBytes(), you can get a byte[] containing an number representation of each letter in the String:
byte[] text = "hello".getBytes();
for(byte b : text) {
System.out.println(b);
}
This gives the same results as:
String text = "hello";
for(char c : text.toCharArray()) {
System.out.println((int) c);
}
This is the easiest way I can possibly think of to achieve this goal. To convert it back to String:
byte[] byteArray = "hello".getBytes();
String string = new String(byteArray);
You can pass the given string in the constructor parameter of StringBuilder class and use the codePointAt(int) method. It returns the ASCII value of character at the index specified.
There are other useful methods also in StringBuilder like codePointBefore(int) and appendCodePoint(int), which allow you to see the codepoint of the character before and append the character with the specified codepoint to the StringBuilder, respectively.
I assume here that the int value of each char should correspond to the Unicode code point of that character. If so, then the solution is trivial: you only need to type-cast between the char and int types. This is because in Java, a char is actually an Integral type just like an int. The char type can hold integer values that represent the code points of 16-bit Unicode characters ('\u0000' to '\uffff' or 0...65535).
The solution is to first, convert the String into a char[] using toCharArray. Then, simply cast each char into an int to get the Unicode code point value:
int capitalACodePoint = (int)'A';
Similarly, cast to char to get the value back:
char capitalA = (char) 65;
A runnable example:
String input = "hello";
List<Integer> codePoints = new ArrayList<>();
for (char c : input.toCharArray()) {
int codePoint = (int)c;
codePoints.add(codePoint);
System.out.println(String.format(
"char$ %d %s equals %d",
codePoints.size(), c, codePoint));
}
StringBuilder sb = new StringBuilder();
for (int codePoint : codePoints) {
sb.append((char) codePoint);
}
System.out.println(sb);
prints out
char$ 1 h equals 104
char$ 2 e equals 101
char$ 3 l equals 108
char$ 4 l equals 108
char$ 5 o equals 111
hello
This code also works with non-ASCII characters. Changing the input to
String input = "©†¿™";
prints out
char$ 1 © equals 169
char$ 2 † equals 8224
char$ 3 ¿ equals 191
char$ 4 ™ equals 8482
©†¿™
char c = '0';
int i = 0;
System.out.println(c == i);
Why does this always returns false?
Although this question is very unclear, I am pretty sure the poster wants to know why this prints false:
char c = '0';
int i = 0;
System.out.println(c == i);
The answer is because every printable character is assigned a unique code number, and that's the value that a char has when treated as an int. The code number for the character 0 is decimal 48, and obviously 48 is not equal to 0.
Why aren't the character codes for the digits equal to the digits themselves? Mostly because the first few codes, especially 0, are too special to be used for such a mundane purpose.
The char c = '0' has the ascii code 48. This number is compared to s, not '0'. If you want to compare c with s you can either do:
if(c == s) // compare ascii code of c with s
This will be true if c = '0' and s = 48.
or
if(c == s + '0') // compare the digit represented by c
// with the digit represented by s
This will be true if c = '0' and s = 0.
The char and int value can not we directly compare we need to apply casting. So need to casting char to string and after string will pars into integer
char c='0';
int i=0;
Answer is like
String c = String.valueOf(c);
System.out.println(Integer.parseInt(c) == i)
It will return true;
Hope it will help you
Thanks
You're saying that s is an Integer and c (from what I see) is a Char.. so there you, that's the problem: Integer vs. Char comparation.