How do I convert a integer representing a character to a string? - java

I am reading a file in Java, which gives me each character as an integer, and then processing each character one at a time. However, I cannot compare that character when it is in integer form, so how can I convert it?
Example:
I want: 93 → A
NOT: 5 → 5
Then, I can compare it with an "if" statement.

Character.toString((char)93);
Use Integer.parseInt() if you are starting with a string containing the characters 9 and 3.

The following should work"
int i = 93;
char c = (char)i;
Basically you typecast the int to its equivalent character.

Just cast like int i = read(); char aChar = (char)i; when appending stringBuilder.append((char)i); or string += (char)i;

Related

How to Output int from char in JAVA after storing it [duplicate]

This question already has answers here:
Char - Java not working as intended / my code
(4 answers)
Closed 3 years ago.
I am seeing a tutorial on udemy and there the instructor says that we can store the integer variable in the char data type. But when I try to print the value ... nothing shows up
I tried assigning the "char one" value to integer variable and then get the output from int variable,It works but why can not I use the char to output the value
public static void main(String[] args) {
char one = 10;
System.out.println(one);
}
If you look at the ASCII table you would see that the character 10 represents the newline character.
This can be proved by the code below:
public static void main(String[] args) {
char one = 10;
//no newline added by print, but println adds a newline implicitly
System.out.print("Test");
System.out.print(one);
System.out.print("Test");
}
The output is:
Test
Test
Although I used System.out.print a newline was still added in the output after the first Test. So you see something was actually printed.
Furthermore, when you pass a char to the System.out.println() the char is converted to its String representation as per the ASCII table by invoking the String.valueOf(char) as char is a primitive.
For Objects when you pass a reference in the System.out.println() the toString() method of the object would be called to get its String representation.
If you change the value to char one = 65 you would see the letter A printed.
In Java char type is an int, therefore they can be converted char <-> int.
When you print an int - you get an integer number. When you print char - you get an ASCII character. char ch = 10 - is not printable character.
char ch = 'A';
System.out.println(ch); // print 'A'
int code = ch;
System.out.println(code); // print 65 - ASCII code of 'A'
Adding to the above answers, if you want to output the int value from the variable "one", a cast would work:
char one = 10;
System.out.println((int) one);
If you take a look at the ASCII Table, you can see the value of 10 is LF which is a new line. If you print this alone, it will appear to be doing nothing because it is just a new line.
However if you modify the code a bit to print some actual characters on both side of the LF char:
char c1 = 70;
System.out.print(c1);
char one = 10;
System.out.print(one);
char c2 = 71;
System.out.print(c2);
This will output:
F
G
On separate lines due to the newline in between, without it they would have printed on the same line.
Additionally you can see on that table 70 corresponds with F, and 71 with G.
Note: Java does not technically use ASCII, but rather a different encoding depending on your environment(commonly UTF-16 or ISO-8859-1), however, the characters are usually equivalent to ASCII for the amount of values the ASCII table contains (a superset). For example char c1 = 202 will print Ê for me, which is not an ASCII value.
You are misinterpreting your output and drawing the wrong conclusion.
A char is a UTF-16 code unit. UTF-16 is a character encoding for the Unicode character set. UTF-16 encodes a Unicode codepoint with one or two UTF-16 code units. Typically, if it might be two code units, you'd use String or char[] instead of char. But if your codepoint is known to take only one UTF-16 code unit, you could use char.
The codepoint you are using is U+000A 'LINE FEED (LF)'. It does take one UTF-16 code unit \u000a, which is convertible from the integer value 0xa or 10. If you inspect your output carefully, you'll "see". Perhaps adding output before and after would help.

Char to int and back again

I want to find an integer representation of a character, then later on find a character representation of an int.
My current solution is this, but it doesn't work:
String s = "A"
Integer b = Character.getNumericValue(s.toCharArray()[0]); // 10
char c = Character.toChars(b)[0]; // (blank)
How should i do this?
There's a misunderstanding in how Character.getNumericValue(char) works.
Returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.
The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
from the java docs.
In other words:
The method getNumericValue does not produce the UTF-16 value of the specified character, but attempts to produce a numeric value - in the sense that '0' will produce 0 - from the given value. And 'A' corresponds to 10 in hex.
But 10 is not the UTF16 value corresponding to 'A'.
A correct way of converting a char to it's corresponding UTF16-value would be to use one of the codepoint-methods from Character. Or if you're absolutely positive, all values will be of the BMP, you can use
char c = 'A';
int i = (int) c;
In this case Character.toChars(int) will also work.
int b = s.charAt(0); // 65
char c = (char) b // 'A'

Why do we write A.charAt(i) but not A.charAt[i]? And why do we write " - 'A' "?

public static int get(String A) // it is a method
{
int count = 1;
for (int i = 0; i < A.length(); i++) // So A reads line (any word, for example "Car"), so I understand that length will be 3 and that java will check all the characters.
{
int num = (A.charAt(i) - 'A') + 1;
count *= num;
}
return count;
}
You write A.charAt(i) because charAt is a function, not an array.
You write A.charAt(i) - 'A' to compute the difference between A's i:th character and the character 'A'.
The class String is an immutable or value object. It doesn't give you direct access to the characters which make up the string, mainly for performance reasons but also since it helps to avoid a whole class of bugs.
That's why you can't use the array access via []. You could call A.getChars() but that would create a copy of the underlying character array.
char is the code for a character. 'A' == 65, for example. See this table. If A.charAt(1) returns 'F' (or 70), then 'F' - 'A' gives you 5. +1 gives 6.
So the code above turns letters into a number. A pattern which you'll see pretty often is charAt(i) - '0' to turn a string into a number.
But the code above is odd in this respect since count *= num produces a pretty random result for the input. To turn the letters into numbers, base 26, it should read count = count * 26 + num.
A.charAt(i) is a method for strings, you could also do A[i] to access the same position directly.
When you do an operation (+ or -) with chars, you get an int.
Java API for charAt() function
charAt() is a java method, not an Array
returns the char value at the specified index.
Syntax:
Here is the syntax of this method:
public char charAt(int index);
Because charAt() is a method that returns a character from a given String, and not an array. Characters are written 'A'. Strings are written "A".
Because charAt is a method within string and it accepts index. String internally maintains char array and it's all hidden from us and hence you have a method not the array itself.
Reason for -'A' is user wants to convert that character to integer. So for e.g. You character is 'B', User wants to convert it into int using ascii value of 'B' which is 66 - ascii value of 'A' which 65
num = 66 - 65 + 1
And do further processing.
because charAt() is a method in java for string it and it returns a character. and 'A' refers to a char type while we write "A" for string type
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29

Convert XSLT function (string-to-codepoints) to Java

How can I "translate" this XSLT code to Java ?
<xsl:value-of select="number(string-to-codepoints(upper-case($char)) - string-to-codepoints('A'))+10"/>
I only know that: "The fn:string-to-codepoints function returns a sequence of xs:integer values representing the Unicode code points."
From the example that is given in (http://www.xsltfunctions.com/xsl/fn_string-to-codepoints.html) :
string-to-codepoints('a') = 97
I found this:
char ch = 'a';
System.out.println(String.format("\\u%04x", (int) ch));
But I get : \u0061
For a single char you can just cast it to int to get the decimal value:
System.out.println((int)ch);
For a String there's .toCharArray() to convert it to a char[] but that isn't quite the same as a "sequence of codepoints" if the String involves Unicode characters outside the BMP (i.e. above U+FFFF), which are represented in Java as a surrogate pair of two char values. To handle surrogates properly you would need to use a technique like the one described in this answer.
To answer the specific question you ask, you can do
number(string-to-codepoints(upper-case($char)) - string-to-codepoints('A'))+10
in Java as
char ch = // wherever you get $char from
int num = Character.toUpperCase(ch) - 'A' + 10;
since char is an integer type in Java and you can add or subtract char values like any other number.
But this will probably only give you a sensible answer when the initial ch is an ASCII letter.
You print the value as unicode escape sequence; XSLT prints a decimal value.
This should work much better:
System.out.println("a".codePointAt(0));

Converting a string of characters to an int array in Java

I'm wondering how I can convert a string like of letters to their numerical value in an array. For example, A is 0, B is 1. I know I need to use like a for loop like this:
for (int i = 0; i < 26; i++), but I'm not sure what code fragment to actually use to do the converting into an int array? Help?
Converting a letter (char) to an integer representing its place in the alphabet is easier than some people realize; all you have to do is:
(int)(c - 'A') // the "distance" between c and 'A' = place of c in alphabet
Loop through the characters of your string and perform this operation for each, storing the results in a new int array.
You can get the each Char by yourString.charAt(i) and then cast it with (int) this will gave you the Corresponding ASCII then subtract from the ASCII of 'A'. You will have what you want
result = (int)yourString.charAt(i) - (int)'A'

Categories