How to get Alphabet from the given integer value? - java

How to get alphabets by the numeric postion in java ?
Suppose i have entered 1 then as a output i need to get A how can i get the alphabets position in java?
Thanks in advance.

Try this
int i = 1;
System.out.println((char)(i+'A'-1));

int charValue = 1; //this is the number you enter
char letter = (char)(charValue+64); //this is the character you want
For lowercase letters, use (charValue+96)

You could use a switch/case statement to manually get each letter however a better solution would be to use the ASCII table to get the letters.
ASCII Table: http://www.ascii-code.com/
public char getLetter(int i)
{
return (char) (i + 64);
}
The above function would return 'A' when i is 1

You have letters/characters, think of them as positions in an array.
int number = 0;
String[] array = new String[] {"a", "b", "c", "..."};
String letter = array[number + 1];

Related

Problem replacing char in char array with a digit

Given a string, I have to replace all vowels with their respective position in the array. However, my code returns some strange symbols instead of numbers. Where's the problem?
String s = "this is my string";
char p = 1;
char[] formatted = s.toCharArray();
for(int i = 0; i < formatted.length; i++) {
if(formatted[i] == 'a' ||formatted[i] == 'e' ||formatted[i] == 'i'
||formatted[i] == 'o' ||formatted[i] == 'u') {
formatted[i] = p;
}
p++;
}
s = String.valueOf(formatted);
System.out.println(s);
P.S: Numbers are bigger than 10
this is my s t r i n g
012345678910 11 12 13 14
The position of i in string is 14 but 14 is not a character; it's a numeric string. It means that you need to deal with strings instead of characters. Split s using "" as the delimiter, process the resulting array and finally join the array back into a string using "" as the delimiter.
class Main {
public static void main(String[] args) {
String s = "this is my string";
String[] formatted = s.split("");
for (int i = 0; i < formatted.length; i++) {
if (formatted[i].matches("(?i)[aeiou]")) {
formatted[i] = String.valueOf(i);
}
}
s = String.join("", formatted);
System.out.println(s);
}
}
Output:
th2s 5s my str14ng
The regex, (?i)[aeiou] specifies case-insensitive match for one of the vowels where (?i) specifies the case-insensitiveness. Test it here.
The character '1' has a different value from the number 1.
You can change
char p = 1;
to
char p = '1';
and I think that will give you what you want, as long you're not trying to insert more than 9 numbers in your string. Otherwise you'll need to cope with inserting extra digits, which you cannot do into a char-array, because it has a fixed length.
the root of the problem is already in the comments,
in java the types make a difference in memory size and its representation
int x = 1;
and
char y = '1'
are not holding the same value, this is because many numerical representations are related with ascii codes and the value you have to assing to y to get the number 1 printed is HEX 0x31 or DEC 49.
take a look at the ascci table

Java int array and char array implementation: why does this work?

I am working on the Kattis problem "abc" in a programming seminar class. The question asks you to input three ints between 0 and 100, and have them match the pattern of another group of three char inputs with the case: A < B < C. Here 'A' will be int with least value, 'B' will be second greatest value, etc. I determined my logic but was unsure how to match values to char. Then a fellow student gave me help with the last line but I didn't get a chance to ask about how it worked. Code I have is as follows:
public class ABC {
public static void main(String[] args) {
var scanner = new Scanner(System.in);
int[] num = new int[3];
for (int i=0; i<num.length; i++) {
num[i] = scanner.nextInt();
}
Arrays.sort(num);
char[] chArr = scanner.next().toCharArray();
for (int i=0; i<chArr.length; i++) {
System.out.println(num[chArr[i] - 'A']); //How does num[chArr[i] - 'A'] work?
}
}
}
Input:
1 2 3
C A B
Output:
3 1 2
So, my question is: How does the expression in the println at the end work? I'm a noob to posting on SO, so any suggestions would be gratefully accepted.
A char in C is literally just an 8-bit integer. It tends to be used to represent ASCII characters, but in code it's an integer. Or in other words, char and uint8 are essentially the same type (in fact, one is an alias for the other in most implementations).
This relationship persists, in some form, into Java. A char is fundamentally an integer that presents itself as a character. Thus, you can do integer arithmetic with characters.
To examine num[chArr[i] - 'A']:
chArr[i] retrieves the character at index i of chArr, an array of chars. Say this is 'C'.
Note that the ASCII value of 'C' is 67.
Note that the ASCII value of 'A' is 65.
67 - 65 = 2. So, 'C' is the 3rd letter of the alphabet, meaning it corresponds to index 2 of num.
Retrieve the value at index 2 of num, and print it.
It's quite easy to understand:
Example :
char a = 'a';
char b = 'b';
// zero = 0 a this point
int zero = a - 'a';
// one = 1; and so on
int one = b - 'b';
Now in your case:
// is equivalent to whatever you enter and the difference of 'A'.
num[chArr[i] - 'A']
But if you enter something whose difference with A is more than the size of nums you are going to get an Array out bounds exception.

How do I count how many digits are in every string of an array?

The instructions are to count how many digits are in every string of an array and assign to numberDigits.
What am I doing wrong here?
public void computeStatistics(String []strings){
numberDigits = 0;
for(String s : strings){
for(int i : s.toCharArray()){
if(i >= 0 || i <= 2)
numberDigits++;
}
}
}
Alternatively, since overall digits count matter, all strings can be concatenated to single and each character can be checked for if it is digit.
public void computeStatistics(String[] strings) {
numberDigits = 0;
//Converting all strings in array to single string
String cmbStr = Arrays.toString(strings);
for (Character c : cmbStr.toCharArray()) {
//checking each character is digit
if (Character.isDigit(c))
numberDigits++;
}
}
Not really sure if i understood your question correctly are you counting the number of digits in a string array?
public int computeStatistics(String []strings){
int numberDigits = 0;
for(String s : strings){
s = s.replaceAll("\D+","");
numberDigits = numberDigits + s.length();
}
return numberDigits;
}
I am assuming that your string is alpha nummeric. Your if condition is wrong. char datatype have integer representations of their corresponding ASCII value. So char a = 'A' when casted to int is actually stored as 65. So the char '0' which is stored in the array you are iterating over is stored in i as 48. You are checking between 0 to 9 ascii codes and hence this code wont work. Either change if condition to
if(i>=48 && i<=57)
Or what i find as a good general policy is to keep char as char.
for(char ch:s.toCharArrat())
if(ch>='0' && ch<='9')
This way you wont have to think about ascii. For converting char '0' to int do the following.
int i = (int)ch - (int)'0';
This will give corresponding integers.

How to get numeric position of alphabets in java? [duplicate]

This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
How to get numeric position of alphabets in java ?
Suppose through command prompt i have entered abc then as a output i need to get 123 how can i get the numeric position of alphabets in java?
Thanks in advance.
String str = "abcdef";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 96; //for lower case
if(temp<=122 & temp>=97)
System.out.print(temp-temp_integer);
}
Output:
123456
#Shiki for Capital/UpperCase letters use the following code:
String str = "DEFGHI";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 64; //for upper case
if(temp<=90 & temp>=65)
System.out.print(temp-temp_integer);
}
Output:
456789
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.
This sounds like homework. If so, please tag it as such.
Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.
Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.
char letter;
for(int i=0; i<text.length(); i++)
{
letter = text.charAt(i);
if(letter>='A' && letter<='Z')
System.out.println((int)letter - 'A'+1);
if(letter>='a' && letter<= 'z')
System.out.println((int)letter - 'a'+1);
}
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.
For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.
just logic I can suggest take two arrays.
one is Char array
and another is int array.
convert ur input string to char array,get the position of char from char and int array.
dont expect source code here
String word = "blah blah";
for(int i =0;i<word.length;++i)
{
if(Character.isLowerCase(word.charAt(i)){
System.out.print((int)word.charAt(i) - (int)'a'+1);
}
else{
System.out.print((int)word.charAt(i)-(int)'A' +1);
}
}

I want to be able to convert numbers into text according to the ASCII decimal table

I am trying to make it so that I can take individual three-character substrings and convert them to integers under the conditions tht the length of the String is a multiple of three. The integers into which the partioned substrings are converted are supposed to function as relative positions in an array that contains all the printing characters of the ASCII table.
String IntMessage = result.toString();
if
{
(IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
for(j=0;j < IntMessage.length()-2;j += 3)
n = Integer.parseInt(IntMessage.substring(j,j+3));
mess += ASCII[n-32];
return mess;
Under otherwise conditions, the method should take the first two characters of the String and initialize them to a variable i. In this case, the variable mess is initialized to the character in the ASCII array with an index of i-32. Then there is a for loop that takes the remaining characters and partitions them into three-digit substrings and they are taken and changed into strings according to their corresponding positions in the ASCII array. The String variables in this array are continuously added on to the the variable mess in order to get the BigInteger to String conversion of the IntMessage String.
int i = Integer.parseInt(IntMessage.substring(0,2));
mess=ASCII[i-32];
for(l=2; l< IntMessage.length() - 2; l+=3)
r = Integer.parseInt(IntMessage.substring(l,l+3));
mess+=ASCII[r-32];
return mess;
For some reason the method isn't working and I was wondering whether I was doing something wrong. I know how to take an input String and convert it into a series of numbers but I want to do the opposite also. Is there anyway you could help?
Based on your description you can use the following methods:
String fromIntMessage(String msg) {
StringBuilder result = new StringBuilder();
for (int x = (msg.length() % 3 - 3) % 3; x < msg.length(); x += 3) {
int chr = Integer.parseInt(msg.substring(Math.max(x, 0), x + 3));
result.append(Character.toString((char) (chr - 32)));
}
return result.toString();
}
String toIntMessage(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
result.append(String.format("%03d", c + 32));
}
return result.charAt(0) == '0' ? result.substring(1) : result.toString();
}
which will give you
toIntMessage("DAA") // => "100097097"
fromIntMessage("100097097") // => "DAA"

Categories