Related
Below is a code snippet,
int a = 1;
char b = (char) a;
System.out.println(b);
But what I get is empty output.
int a = '1';
char b = (char) a;
System.out.println(b);
I will get 1 as my output.
Can somebody explain this? And if I want to convert an int to a char as in the first snippet, what should I do?
int a = 1;
char b = (char) a;
System.out.println(b);
will print out the char with Unicode code point 1 (start-of-heading char, which isn't printable; see this table: C0 Controls and Basic Latin, same as ASCII)
int a = '1';
char b = (char) a;
System.out.println(b);
will print out the char with Unicode code point 49 (one corresponding to '1')
If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.
If you want to convert an int seen as a Unicode code point, you can use Character.toChars(48) for example.
My answer is similar to jh314's answer but I'll explain a little deeper.
What you should do in this case is:
int a = 1;
char b = (char)(a + '0');
System.out.println(b);
Here, we used '0' because chars are actually represented by ASCII values. '0' is a char and represented by the value of 48.
We typed (a + '0') and in order to add these up, Java converted '0' to its ASCII value which is 48 and a is 1 so the sum is 49. Then what we did is:
(char)(49)
We casted int to char. ASCII equivalent of 49 is '1'. You can convert any digit to char this way and is smarter and better way than using .toString() method and then subtracting the digit by .charAt() method.
It seems like you are looking for the Character.forDigit method:
final int RADIX = 10;
int i = 4;
char ch = Character.forDigit(i, RADIX);
System.out.println(ch); // Prints '4'
There is also a method that can convert from a char back to an int:
int i2 = Character.digit(ch, RADIX);
System.out.println(i2); // Prints '4'
Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).
int a = 1;
char b = (char) a;
System.out.println(b);
hola, well i went through the same problem but what i did was the following code.
int a = 1
char b = Integer.toString(a).charAt(0);
System.out.println(b);
With this you get the decimal value as a char type. I used charAt() with index 0 because the only value into that String is 'a' and as you know, the position of 'a' into that String start at 0.
Sorry if my english isn't well explained, hope it helps you.
you may want it to be printed as '1' or as 'a'.
In case you want '1' as input then :
int a = 1;
char b = (char)(a + '0');
System.out.println(b);
In case you want 'a' as input then :
int a = 1;
char b = (char)(a-1 + 'a');
System.out.println(b);
java turns the ascii value to char :)
int a = 1;
char b = (char) (a + 48);
In ASCII, every char have their own number. And char '0' is 48 for decimal, '1' is 49, and so on. So if
char b = '2';
int a = b = 50;
Nobody has answered the real "question" here: you ARE converting int to char correctly; in the ASCII table a decimal value of 01 is "start of heading", a non-printing character. Try looking up an ASCII table and converting an int value between 33 and 7E; that will give you characters to look at.
Whenever you type cast integer to char it will return the ascii value of that int (once go through the ascii table for better understanding)
int a=68;
char b=(char)a;
System.out.println(b);//it will return ascii value of 68
//output- D
If we are talking about class types - not primitives, the following trick has to be done:
Integer someInt;
Character someChar;
someChar = (char)Integer.parseInt(String.valueOf(someInt));
First, convert the int (or another type) to String,
int a = 1;
String value = String.valueOf(a);
Then, convert that String to char.
char newValue = value.charAt(0);
You can avoid empty output in this way...
System.out.println(newValue);
In java a char is an int. Your first snippet prints out the character corresponding to the value of 1 in the default character encoding scheme (which is probably Unicode). The Unicode character U+0001 is a non-printing character, which is why you don't see any output.
If you want to print out the character '1', you can look up the value of '1' in the encoding scheme you are using. In Unicode this is 49 (the same as ASCII). But this will only work for digits 0-9.
You might be better off using a String rather than a char, and using Java's built-in toString() method:
int a = 1;
String b = toString(a);
System.out.println(b);
This will work whatever your system encoding is, and will work for multi-digit numbers.
if you want to print ascii characters based on their ascii code and do not want to go beyond that (like unicode characters), you can define your variable as a byte, and then use the (char) convert. i.e.:
public static void main(String[] args) {
byte b = 65;
for (byte i=b; i<=b+25; i++) {
System.out.print((char)i + ", ");
}
BTW, the ascii code for the letter 'A' is 65
Make sure the integer value is ASCII value of an alphabet/character.
If not then make it.
for e.g. if int i=1
then add 64 to it so that it becomes 65 = ASCII value of 'A'
Then use
char x = (char)i;
print x
// 'A' will be printed
There is one method by which int can be converted to char and even without using ASCII values.
Example:
int i = 2;
char ch = Integer.toString(i).charAt(0);
System.out.println(ch);
Explanation :
First the integer is converted to string and then by using String function charAt(), character is extracted from the string. As the integer only has one single digit, the index 0 is given to charAt() function.
My solution is for converting lower case alphabets (a-z) to (0-25) and vice versa.
My answer is for a specific use-case it is not generic solution my solution will help you if you want to store the frequency of character into an integer array of size 26 instead of using Hashmap<Character,Integer>
----> for converting 0 to 25 into a-z
char ch=(char)(0+'a'); // output 'a' // input 0(as integer)
char ch=(char)(25+'a'); // output 'z' // input 25(as integer)
---->for converting a to z into 0-25
int freq='a'-'a' // output 0 // input 'a'
int freq='b'-'a' // output 1 // input 'b'
int freq='c'-'a' // output 2 // input 'c'
int freq='z'-'a' // output 25 // input 'z'
Again this approach will help you to get the frequency of characters as well as characters
public class Main
{
public static void main(String[] args) {
String s="rajatfddfdf";
int freq[]= new int[26];
for(int i=0;i<s.length();i++){
char characterAtIndex=s.charAt(i);
freq[characterAtIndex-'a']+=1;
}
for(int i=0;i<26;i++){
System.out.println((char)('a'+i)+" frequency="+freq[i]);
}
}
}
by using the above code we can get the frequency as well as character using integer array of size 26 . We can write if-else logic if you don't want to include the character with frequency 0.
look at the following program for complete conversion concept
class typetest{
public static void main(String args[]){
byte a=1,b=2;
char c=1,d='b';
short e=3,f=4;
int g=5,h=6;
float i;
double k=10.34,l=12.45;
System.out.println("value of char variable c="+c);
// if we assign an integer value in char cariable it's possible as above
// but it's not possible to assign int value from an int variable in char variable
// (d=g assignment gives error as incompatible type conversion)
g=b;
System.out.println("char to int conversion is possible");
k=g;
System.out.println("int to double conversion is possible");
i=h;
System.out.println("int to float is possible and value of i = "+i);
l=i;
System.out.println("float to double is possible");
}
}
hope ,it will help at least something
If you want to convert a character to its corresponding integer, you can do something like this:
int a = (int) 'a';
char b = (char) a;
System.out.println(b);
This happens because in ASCII there are some items that can not be printed normally.
For example, numbers 97 to 122 are integers corresponding to the lowercase letters a to z.
public class String_Store_In_Array
{
public static void main(String[] args)
{
System.out.println(" Q.37 Can you store string in array of integers. Try it.");
String str="I am Akash";
int arr[]=new int[str.length()];
char chArr[]=str.toCharArray();
char ch;
for(int i=0;i<str.length();i++)
{
arr[i]=chArr[i];
}
System.out.println("\nI have stored it in array by using ASCII value");
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nI have stored it in array by using ASCII value to original content");
for(int i=0;i<arr.length;i++)
{
ch=(char)arr[i];
System.out.print(" "+ch);
}
}
}
I want to decrement lowercase letters to lowercase letters only. I do this by taking the ASCII value of the character and decrement it. But for example if I decrement a by 2, the answer should be y. Not a symbol or a uppercase letter.
int charValue = temps.charAt(i);
String increment = String.valueOf( (char) (charValue - (m) ));
if((charValue - m) < 65){
int diff = 65 - (charValue - m);
increment = String.valueOf((char) (91 - diff));
}else if((charValue - m) < 97 && (charValue - m) >= 91){
int diff = 97 - (charValue - m);
increment = String.valueOf((char) (123 - diff));
}
System.out.print(increment);
This is the code I have so far. The problem with this is if I decrement a by 8, it shows an upper case letter.
EX:- if i input 'a' and m value as 8, the expected output should be 's'. But im getting 'Y'
Here charToBeChanged is the lowercase character that you want to shift. And decrementValue is the value by how much you want to shift. In the main post you said:
if i input 'a' and m value as 8, the expected output should be 's'
So, here charToBeChanged is a and decrementValue is 8.
System.out.println((char) ((charToBeChanged - 'a' + 26 - decrementValue) % 26 + 'a'));
For a moment forget about the ASCII code table (or any other) and suppose that the letters are numbered sequentially from 1 (for a) to 26 (for z). The problem is now a simple matter of arithmetic modulo 26. In pseudocode, decrementing a by 2 translates into something like
Mod[(1-2),26]
which is 25, the codepoint for y in the sequential code outlined above.
My Java is laughable so I'll leave it to OP to take care of the translation between ASCII code values and sequential code values, and the implementation of a function to perform the operation.
It pretty much depends on your definition of 'lowercase letter'. Is ö lowercase letter? For me, it is. Or č? I have it in my name, so definitely I consider it lowercase letter.
Therefore the program needs to define its own sequence of considered lowercase letters. Note that for the example I only included the characters a to g and x to z, but anything (including \u010D for č or \u00f6 for ö) could be included in the list.
public class DecrementChars {
List<Character> validLowercaseChars
= Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'x','y', 'z');
boolean isLowercaseletter(char letter) {
return validLowercaseChars.contains(letter);
}
char decrement(char input, int decrement) {
if(!isLowercaseletter(input)) {
throw new IllegalArgumentException();
}
int inputIndex = validLowercaseChars.indexOf(input);
int size = validLowercaseChars.size();
int outputIndex = (size + inputIndex - decrement) % size;
return validLowercaseChars.get(outputIndex);
}
#Test(expected=IllegalArgumentException.class)
public void thatDecrementOfInvalidInputThrows() {
decrement('9', 1);
}
#Test
public void thatDecrementOfbByOneGetsa() {
Assert.assertEquals('a', decrement('b', 1));
}
#Test
public void thatDecrementOfaByTwoGetsy() {
Assert.assertEquals('y', decrement('a', 2));
}
}
You could use the equals() and to...Case methods to check what the input was and then convert the output to the same case.
if(charValue.equals("[a-z; A-z]")){
if(charValue.equals(increment)){
System.out.println(increment);
}
if(!charValue.equals(increment)){
System.out.println(increment.toUpperCase());
}
if(!charValue.equals(increment)){
System.out.println(increment.toLowerCase());
}
}else{
System.out.println("Not a letter");
}
Note that I haven't tested this and I am a bit rusty with Regex.
Try with this:
int charValue = 'a';
int m = 8;
String increment = null;
//if a-z
if(charValue>96 && charValue<123){
int difference = charValue - m;
if(difference < 97)
difference+=26;
increment = String.valueOf((char) difference);
}
System.out.println(increment);
I have to handle some strings, I should put them N positions to left to organize the string.
Here's my code for while:
private String toLeft() {
String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Example
byte lpad = 2; // Example
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
sb.append((char) (word.charAt(i) - lpad));
}
return sb.toString();
}
It's working for inputs that don't have to move many times...
So, the problem is that when the number N of positions to move is a little bit large (like 10), it returns me non letters, like in the example below, what can I do to prevent it?
Ex.: ABCDEFGHIJKLMNOPQRSTUVWXYZ if I move each char 10 positions to left it returns 789:;<=>?#ABCDEFGHIJKLMNOP while it must return QRSTUVWXYZABCDEFGHIJKLMNOP.
Some inputs and their expected outputs:
VQREQFGT // 2 positions to left == TOPCODER
ABCDEFGHIJKLMNOPQRSTUVWXYZ // 10 positions to left == QRSTUVWXYZABCDEFGHIJKLMNOP
LIPPSASVPH // 4 positions to left == HELLOWORLD
I think you have misunderstood what your (homework?) requirements are asking you to do. Lets look at your examples:
VQREQFGT // 2 positions to left == TOPCODER
Makes sense. Each character in the output is two characters before the corresponding input. But read on ...
ABCDEFGHIJKLMNOPQRSTUVWXYZ // 10 positions to left == QRSTUVWXYZABCDEFGHIJKLMNOP
Makes no sense (literally). The letter Q is not 10 characters before A in the alphabet. There is no letter in the alphabet that is before A in the alphabet.
OK so how do you get from A to Q in 10 steps?
Answer ... you wrap around!
A, Z, Y, X, W, V, U, T, S, R, Q ... 10 steps: count them.
So what the requirement is actually asking for is N characters to the left with wrap around. Even if they don't state this clearly, it is the only way that the examples "work".
But you just implemented N characters to the left without wrap around. You need to implement the wrap around. (I won't show you how, but there lots of ways to do it.)
There's another thing. The title of the question says "Decrement only letters" ... which implies to me that your requirement is saying that characters that are not letters should not be decremented. However, in your code you are decrementing every character in the input, whether or not it is a letter. (The fix is simple ... and you should work it out for yourself.)
what can I do to prevent it?
You make it wrap around.
If you want a value to go from 10 to 19 and then start at 10 again, in each iteration you subtract 10, increase by one, take the remainder of that divided by 20, and add 10 again.
Only here, 10 is 'A', 19 is Z, and instead of increasing by one, we add or subtract n.
private String toLeft() {
String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Example
byte lpad = 10; // Example
StringBuilder sb = new StringBuilder();
int n = -lpad; // I'm using n here to I can use '+ n' below
for (int i = 0; i < word.length(); i++) {
int shifted = word.charAt(i) - 'A' + n;
shifted %= ('Z' - 'A' + 1); // This is for positive n
while(shifted < 0) // And this for negative ones
{
shifted += ('Z' - 'A' + 1);
}
sb.append((char)(shifted + 'A'));
}
return sb.toString();
}
Please read #StephenC's excellent answer about wrap-around. In short, you don't shift left, you rotate left, such that B → A → Z → Y. When you rotate, you wrap around to the other end.
So, for letters you want A-Z to rotate. The easiest rotation method is using modulus (%).
Your logic will be as follows:
Convert letters A-Z into numbers 0-25: n = ch - 'A'
Apply shift and wrap around. Since you're shifting left, you're subtracting from the number, so to prevent negative numbers, you start by shifting a full cycle to the right: n = (n + 26 - shift) % 26
Convert numbers back to letters: ch = (char)(n + 'A')
Here is the code:
private static String rotateLeft(String text, int count) {
char[] buf = text.toCharArray();
for (int i = 0; i < buf.length; i++)
buf[i] = (char)((buf[i] - 'A' + 26 - count) % 26 + 'A');
return new String(buf);
}
Of course, you should validate input, and test your code:
private static String rotateLeft(String text, int count) {
char[] buf = text.toCharArray();
if (count <= 0 || count >= 26)
throw new IllegalArgumentException("Invalid count: " + count);
for (char ch : buf)
if (ch < 'A' || ch > 'Z')
throw new IllegalArgumentException("Invalid character: " + ch);
for (int i = 0; i < buf.length; i++)
buf[i] = (char)((buf[i] - 'A' + 26 - count) % 26 + 'A');
return new String(buf);
}
public static void main(String[] args) {
System.out.println(rotateLeft("VQREQFGT", 2));
System.out.println(rotateLeft("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10));
System.out.println(rotateLeft("LIPPSASVPH", 4));
}
OUTPUT
TOPCODER
QRSTUVWXYZABCDEFGHIJKLMNOP
HELLOWORLD
Here is a short program that counts the letters of any given word entered by the user.
I'm trying to figure out what the following lines actually do in this program:
counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing
System.out.println((char)('a' + i) // I don't get what the 'a' + i actually does.
import java.util.Scanner;
public class Listing9_3 {
public static void main(String[] args) {
//Create a scanner
Scanner input = new Scanner (System.in);
System.out.println("Enter a word to find out the occurences of each letter: ");
String s = input.nextLine();
//Invoke the count Letters Method to count each letter
int[] counts = countLetters(s.toLowerCase());
//Display results
for(int i = 0; i< counts.length; i++){
if(counts[i] != 0)
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1)? " time" : " times"));
***//I don't understand what the 'a' + i is doing
}
}
public static int[] countLetters(String s) {
int[] counts = new int [26]; // 26 letters in the alphabet
for(int i = 0; i < s.length(); i++){
if(Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
***// I don't understand what the - 'a' is doin
}
return counts;
}
}
Characters are a kind of integer in Java; the integer is a number associated with the character on the Unicode chart. Thus, 'a' is actually the integer 97; 'b' is 98, and so on in sequence up through 'z'. So s.charAt(i) returns a character; assuming that it is a lower-case letter in the English alphabet, subtracting 'a' from it gives the result 0 for 'a', 1 for 'b', 2 for 'c', and so on.
You can see the first 4096 characters of the Unicode chart at http://en.wikibooks.org/wiki/Unicode/Character_reference/0000-0FFF (and there will be references to other pages of the chart as well). You'll see 'a' there as U+0061 (which is hex, = 97 decimal).
Because you want your array to contains only the count of each letter from 'a' to 'z'.
So to index correctly each count of the letter within the array you would need a mapping letter -> index with 'a' -> 0, 'b' -> 1 to 'z' -> 25.
Each character is represented by a integer value on 16 bits (so from 0 to 65,535). You're only interested from the letters 'a' to 'z', which have respectively the values 97 and 122.
How would you get the mapping?
This can be done using the trick s.charAt(i) - 'a'.
This will ensure that the value returned by this operation is between 0 and 25 because you know that s.charAt(i) will return a character between 'a' and 'z' (you're converting the input of the user in lower case and using Character.isLetter)
Hence you got the desired mapping to count the occurences of each letter in the word.
On the other hand, (char)('a' + i) does the reverse operation. i varies from 0 to 25 and you respectively got the letters from 'a' to 'z'. You just need to cast the result of the addition to char otherwise you would see its unicode value be printed.
counts[s.charAt(i) - 'a']++; // I don't understand what the - 'a' is doing
assume charAT(i) is 'z'
now z-a will be equal to 25 (subtract the unicode / ASCII values).
so counts[25]=counts[25]+1; // just keeps track of count of each character
Below is a code snippet,
int a = 1;
char b = (char) a;
System.out.println(b);
But what I get is empty output.
int a = '1';
char b = (char) a;
System.out.println(b);
I will get 1 as my output.
Can somebody explain this? And if I want to convert an int to a char as in the first snippet, what should I do?
int a = 1;
char b = (char) a;
System.out.println(b);
will print out the char with Unicode code point 1 (start-of-heading char, which isn't printable; see this table: C0 Controls and Basic Latin, same as ASCII)
int a = '1';
char b = (char) a;
System.out.println(b);
will print out the char with Unicode code point 49 (one corresponding to '1')
If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.
If you want to convert an int seen as a Unicode code point, you can use Character.toChars(48) for example.
My answer is similar to jh314's answer but I'll explain a little deeper.
What you should do in this case is:
int a = 1;
char b = (char)(a + '0');
System.out.println(b);
Here, we used '0' because chars are actually represented by ASCII values. '0' is a char and represented by the value of 48.
We typed (a + '0') and in order to add these up, Java converted '0' to its ASCII value which is 48 and a is 1 so the sum is 49. Then what we did is:
(char)(49)
We casted int to char. ASCII equivalent of 49 is '1'. You can convert any digit to char this way and is smarter and better way than using .toString() method and then subtracting the digit by .charAt() method.
It seems like you are looking for the Character.forDigit method:
final int RADIX = 10;
int i = 4;
char ch = Character.forDigit(i, RADIX);
System.out.println(ch); // Prints '4'
There is also a method that can convert from a char back to an int:
int i2 = Character.digit(ch, RADIX);
System.out.println(i2); // Prints '4'
Note that by changing the RADIX you can also support hexadecimal (radix 16) and any radix up to 36 (or Character.MAX_RADIX as it is also known as).
int a = 1;
char b = (char) a;
System.out.println(b);
hola, well i went through the same problem but what i did was the following code.
int a = 1
char b = Integer.toString(a).charAt(0);
System.out.println(b);
With this you get the decimal value as a char type. I used charAt() with index 0 because the only value into that String is 'a' and as you know, the position of 'a' into that String start at 0.
Sorry if my english isn't well explained, hope it helps you.
you may want it to be printed as '1' or as 'a'.
In case you want '1' as input then :
int a = 1;
char b = (char)(a + '0');
System.out.println(b);
In case you want 'a' as input then :
int a = 1;
char b = (char)(a-1 + 'a');
System.out.println(b);
java turns the ascii value to char :)
int a = 1;
char b = (char) (a + 48);
In ASCII, every char have their own number. And char '0' is 48 for decimal, '1' is 49, and so on. So if
char b = '2';
int a = b = 50;
Nobody has answered the real "question" here: you ARE converting int to char correctly; in the ASCII table a decimal value of 01 is "start of heading", a non-printing character. Try looking up an ASCII table and converting an int value between 33 and 7E; that will give you characters to look at.
Whenever you type cast integer to char it will return the ascii value of that int (once go through the ascii table for better understanding)
int a=68;
char b=(char)a;
System.out.println(b);//it will return ascii value of 68
//output- D
If we are talking about class types - not primitives, the following trick has to be done:
Integer someInt;
Character someChar;
someChar = (char)Integer.parseInt(String.valueOf(someInt));
First, convert the int (or another type) to String,
int a = 1;
String value = String.valueOf(a);
Then, convert that String to char.
char newValue = value.charAt(0);
You can avoid empty output in this way...
System.out.println(newValue);
In java a char is an int. Your first snippet prints out the character corresponding to the value of 1 in the default character encoding scheme (which is probably Unicode). The Unicode character U+0001 is a non-printing character, which is why you don't see any output.
If you want to print out the character '1', you can look up the value of '1' in the encoding scheme you are using. In Unicode this is 49 (the same as ASCII). But this will only work for digits 0-9.
You might be better off using a String rather than a char, and using Java's built-in toString() method:
int a = 1;
String b = toString(a);
System.out.println(b);
This will work whatever your system encoding is, and will work for multi-digit numbers.
if you want to print ascii characters based on their ascii code and do not want to go beyond that (like unicode characters), you can define your variable as a byte, and then use the (char) convert. i.e.:
public static void main(String[] args) {
byte b = 65;
for (byte i=b; i<=b+25; i++) {
System.out.print((char)i + ", ");
}
BTW, the ascii code for the letter 'A' is 65
Make sure the integer value is ASCII value of an alphabet/character.
If not then make it.
for e.g. if int i=1
then add 64 to it so that it becomes 65 = ASCII value of 'A'
Then use
char x = (char)i;
print x
// 'A' will be printed
There is one method by which int can be converted to char and even without using ASCII values.
Example:
int i = 2;
char ch = Integer.toString(i).charAt(0);
System.out.println(ch);
Explanation :
First the integer is converted to string and then by using String function charAt(), character is extracted from the string. As the integer only has one single digit, the index 0 is given to charAt() function.
My solution is for converting lower case alphabets (a-z) to (0-25) and vice versa.
My answer is for a specific use-case it is not generic solution my solution will help you if you want to store the frequency of character into an integer array of size 26 instead of using Hashmap<Character,Integer>
----> for converting 0 to 25 into a-z
char ch=(char)(0+'a'); // output 'a' // input 0(as integer)
char ch=(char)(25+'a'); // output 'z' // input 25(as integer)
---->for converting a to z into 0-25
int freq='a'-'a' // output 0 // input 'a'
int freq='b'-'a' // output 1 // input 'b'
int freq='c'-'a' // output 2 // input 'c'
int freq='z'-'a' // output 25 // input 'z'
Again this approach will help you to get the frequency of characters as well as characters
public class Main
{
public static void main(String[] args) {
String s="rajatfddfdf";
int freq[]= new int[26];
for(int i=0;i<s.length();i++){
char characterAtIndex=s.charAt(i);
freq[characterAtIndex-'a']+=1;
}
for(int i=0;i<26;i++){
System.out.println((char)('a'+i)+" frequency="+freq[i]);
}
}
}
by using the above code we can get the frequency as well as character using integer array of size 26 . We can write if-else logic if you don't want to include the character with frequency 0.
look at the following program for complete conversion concept
class typetest{
public static void main(String args[]){
byte a=1,b=2;
char c=1,d='b';
short e=3,f=4;
int g=5,h=6;
float i;
double k=10.34,l=12.45;
System.out.println("value of char variable c="+c);
// if we assign an integer value in char cariable it's possible as above
// but it's not possible to assign int value from an int variable in char variable
// (d=g assignment gives error as incompatible type conversion)
g=b;
System.out.println("char to int conversion is possible");
k=g;
System.out.println("int to double conversion is possible");
i=h;
System.out.println("int to float is possible and value of i = "+i);
l=i;
System.out.println("float to double is possible");
}
}
hope ,it will help at least something
If you want to convert a character to its corresponding integer, you can do something like this:
int a = (int) 'a';
char b = (char) a;
System.out.println(b);
This happens because in ASCII there are some items that can not be printed normally.
For example, numbers 97 to 122 are integers corresponding to the lowercase letters a to z.
public class String_Store_In_Array
{
public static void main(String[] args)
{
System.out.println(" Q.37 Can you store string in array of integers. Try it.");
String str="I am Akash";
int arr[]=new int[str.length()];
char chArr[]=str.toCharArray();
char ch;
for(int i=0;i<str.length();i++)
{
arr[i]=chArr[i];
}
System.out.println("\nI have stored it in array by using ASCII value");
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nI have stored it in array by using ASCII value to original content");
for(int i=0;i<arr.length;i++)
{
ch=(char)arr[i];
System.out.print(" "+ch);
}
}
}