When doing competitive programming in java, I felt that the handling of char type was complicated, so I decided to summarize it.
The char type stores Unicode characters in hexadecimal. At this time, the char type has a numerical value when the Unicode character is converted into a decimal number. For example, if you assign a char type '1' to an int type variable, you can treat it as a numerical value of 49.
int c = 'a';
System.out.println(c);
//49 is output
(char) (numerical value) becomes the char corresponding to the numerical value.
char c = (char)97;
System.out.println(c);
//'a'Is output
There are times when you want to convert a char type number to an int type, such as when you get a number as a char type with String.charAt (index) from a character string that lists the numbers. As mentioned above, if you try to use the char type as an int type as it is, it will be a different number. In this case, Character.getNumericValue (char c) is used.
char c = '1';
int value = Character.getNumericValue(c);
//value == 1
Conversely, if you want to convert an int type number to a char type, add it to '0'.
int a = 1;
char c = (char)('0'+a);
//c == '1'
The numbers of the char type alphabet are continuous, such as 97 for char type'a'and 98 for'b'. Therefore, each alphabet can be handled by the for statement as follows.
char c = 'a';
for(int i = 0; i < 26; i++){
System.out.print(c);
c++;
}
//abc...Is output
Consider storing in an array how many of each alphabet is contained in a string.
String S = "abbcccdefg";
int[] a = new int[26];
for(int i = 0; i < S.length(); i++)
a[S.charAt(i)-'a']++;
Even if you don't remember the number of'a', there is no problem because'a' can be treated as a number.
Recommended Posts