If I have a char, for example:
char letter = 'g'
is there a way for me to find out where in the alphabet this letter is? (assuming it is in the alphabet)
So for clarification, the answer for letter would be 7, since g is the 7'th letter in the alphabet.
For starters, you can always get the ASCII int value for a character in Java by simply casting that character to an int as follows:
char letter = 'g';
int ascii = (int) letter; # ascii = 103
To get the 1-based position in the alphabet, you can offset this value keeping in mind that character a has a value of 97:
int getPosition(char input) {
char smalla = 'a';
int alphabetStart = (int) smalla; # alphabetStart = 97
int position = (int) input - alphabetStart + 1;
return position;
}
Keep in mind that I have only considered lowercase letters of the alphabet in my solution. Uppercase characters have ASCII values which run from 65 (A) to 90 (Z), and the solution to take those into account would be a bit more complex.
Use indexOf() to get position of character from abcdefg... string
Here is the simple solution.
public static int getCharPosition(char c)
{
String line = "abcdefghijklmnopqrstuvwxyz";
int position = line.indexOf(String.valueOf(c).toLowerCase())+1;
return position;
}
Input : z
Output : 26
As being said in the comments, the easiest way to find index of a char is:
c.toLowerCase() - 'a' + 1
In the ASCII table each letter has an ordinal number. You can get the ordinal number of a char by casting it to int.
The lower case letter a has an ordinal number of 97, so you have to substract it from your letter's ordinal number. Since the ASCII table starts at ordinal number 0, substract an additional 1.
Java code:
char letter = 'g';
int asciiNumber = (int)letter; // 103
final int offset = 97 - 1; // 97 is ASCII code for 'a', -1 since ASCII table starts at 0
int numberInAlphabet = asciiNumber - offset;
System.out.println("Position of letter '" + letter + "': " + numberInAlphabet);
To handle both lowercase and uppercase you can do something like this :
public int alphabetPosition(char c) {
int a='a';
int position=(String.valueOf(c).toLowerCase().codePointAt(0))-a+1;
return position;
}
public class SearchAlphabet {
public static void main(String args[])
{
char letter='d';
int ascii=97; //ascii value of a
int counter=1;
for(int a=0;a<=27;a++)
{
if(ascii==(int)letter)
{
System.out.println("Position");
System.out.println(counter);
break;
}
ascii++;
counter++;
}
}
}
Here,we start counter from 1 and incremented by 1 on every iteration after matching the given character ascii.And after matching the with concern character, we print the counter value.
Related
This question already has answers here:
Java: Subtract '0' from char to get an int... why does this work?
(10 answers)
Closed 3 years ago.
I am reading about the search function which checks the Trie data structure, but I don't understand why the code subtract the character a to get the index. Can anyone help? Thanks in advance!
// Returns true if key presents in trie, else false
static boolean search(String key)
{
int level;
int length = key.length();
int index;
TrieNode pCrawl = root;
for (level = 0; level < length; level++)
{
index = key.charAt(level) - 'a';
if (pCrawl.children[index] == null)
return false;
pCrawl = pCrawl.children[index];
}
return (pCrawl != null && pCrawl.isEndOfWord);
}
Assuming key contains only lower case English letters, key.charAt(i) = 'a' maps each lower case letter to an index between 0 (for 'a') and 25 (for 'z').
The children array probably has a length of 26, and each element of that array corresponds with a latter between 'a' and 'z'.
In java whenever we subtract a character from another character it converts both characters into ascii code and return their subtraction like:- ascii code of a is 97 & ascii code of b is 98 ( 'b' - 'a' ) will return 1
In your code when you will pass string in this method it will return subtraction of 'a' from each character of string
char variables are actually integral, reflecting the Unicode value of the corresponding char. 'a' is thus in fact 97; 'b' is 98 etc. Subtracting 97 from a character will translate characters between 'a' and 'z' to numbers between 0 and 25.
I have written a small piece of code where you enter a 3 digit number via the command line, and then it detects how many 5's are in the code.
public class fivedet {
public static void main (String[] args) {
String input = args[0];
int[] a = {0,0,0};
int x = 0;
int y = 0;
int z = 0;
for(int i = 0; i<input.length();i++) {
a[i] = input.charAt(i) - 48;
}
if(a[0]==5) {
x=5;
}
if(a[1]==5) {
y=5;
}
if(a[2]==5) {
z=5;
}
System.out.println("5 digits here:" + x + y + z);
}
}
My main question is why I require the -48 term after the input.charAt(i) method in order for each value in a[] to be equal to the actual number I input.
For example I enter
java fivedet 505
and without the -48 the array a[]={53,48,53} instead of a[]={5,0,5} and I unfortunately am not experienced enough with coding java (began learning 3 months ago) to understand why this is happening.
I also do want to develop it to be able to detect different digits and for different lengths of input numbers.
I would appreciate any insight as to why this happens.
Subtracting 48 is a quick but slightly confusing way of converting from a character to an integer. It so happens that the character code for each digit is 48 away from its numeric value.
See this table of ASCII values. (Java uses unicode, not ascii - strings are UTF-16 internally - but the values are valid in this specific case). So the character '0' has the value 48; the character '9' has the value 57.
Another way of doing this would be to take 1-character substrings of input, then call Integer.parseInt() on that string, converting "1" to 1, "2" to 2, etc.
You don’t need to convert to int in order to detect character 5. Just count them as chars.
for (char i : args[0].toCharArray()) {
System.out.print(i == '5' ? i : '0');
}
Also this question has good answers to count occurrences of a char in string
I am trying to come up with a function that accepts a character and a number. The number is the number of times the character should be "rotated". The accepted ASCII codes are 32 to 126.
Example of rotate = If a character "A" was rotated twice, it would end up as the character "C". If "A" was rotated three times, it would end up as the letter "D". If you look at the ASCII table:
http://www.jimprice.com/ascii-0-127.gif
Given my limit of the ASCII value being 32 to 126... ascii value 065 rotated would be ascii value 067. ascii value 124 rotated 5 times would be ascii value 34.
For example:
if I passed the function "!" (ASCII code 33) and the number 2, the
output character should be "#" (ASCII code 35).
if I passed "}"
(ASCII code 125) and the number 3, I should get the output character
"!" (ASCII code 33).
What is the best way to accomplish this in java (can it support negative numbers for the distance to rotate instead of just positive if you want to rotate the other way around)?
Try something like:
static char rotate(char c, int distance) {
assert 32 <= c && c < 127;
if (distance < 0) distance = distance % (127 - 32) + 127 - 32;
return (char) ((c + distance - 32) % (127 - 32) + 32);
}
Edit: Added the if (distance... line to support negative distances.
Do like this
public static char numToChar(int num,int rotate){
int result = num+rotate;
if(result>126){
result =31+(result-126);
}
return (char)result;
}
System.out.println(numToChar(33,2));
System.out.println(numToChar(125,3));
Output
#
!
You could use this approach
public static char rotateChar(char in, int shift) {
/* cast char to int */
int v = (int) in;
/* to cover wrap-around */
v += (shift % 95);
/* 32 - 126 = -95 */
return (char) ((v > 126) ? v - 95 : v);
}
public static void main(String[] args) {
System.out.printf("! + 2 = %s\n",
String.valueOf(rotateChar('!', 2)));
System.out.printf("} + 3 = %s\n",
String.valueOf(rotateChar('}', 3)));
System.out.printf("b - 1 = %s\n",
String.valueOf(rotateChar('b', -1)));
}
! + 2 = #
} + 3 = !
b - 1 = a
Try This.
public static void main(String[] args) {
String ascii;
String rotate;
Scanner in = new Scanner(System.in);
System.out.println("Enter ASCII Character");
ascii = in.nextLine();
System.out.println("Enter Rotate value");
rotate = in.nextLine();
int output=(Integer.parseInt(ascii)+Integer.parseInt(rotate))% 126;
if(output<32) output=output+32;
System.out.println("output="+output);
System.out.println(Character.toString ((char) output));
}
Can someone please explain to me what is going on here:
char c = '+';
int i = (int)c;
System.out.println("i: " + i + " ch: " + Character.getNumericValue(c));
This prints i: 43 ch:-1. Does that mean I have to rely on primitive conversions to convert char to int? So how can I convert a Character to Integer?
Edit: Yes I know Character.getNumericValue returns -1 if it is not a numeric value and that makes sense to me. The question is: why does doing primitive conversions return 43?
Edit2: 43 is the ASCII for +, but I would expect the cast to not succeed just like getNumericValue did not succeed. Otherwise that means there are two semantic equivalent ways to perform the same operation but with different results?
Character.getNumericValue(c)
The java.lang.Character.getNumericValue(char ch) 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.
This method returns the numeric value of the character, as a
nonnegative int value;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 if the character has no numeric value.
And here is the link.
As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:
int value = (int)c.charValue();
Try any one of the below. These should work:
int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');
From the Javadoc for Character#getNumericValue:
If the character does not have a numeric value, then -1 is returned.
If the character has a numeric value that cannot be represented as a
nonnegative integer (for example, a fractional value), then -2 is
returned.
The character + does not have a numeric value, so you're getting -1.
Update:
The reason that primitive conversion is giving you 43 is that the the character '+' is encoded as the integer 43.
43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back.
http://en.wikipedia.org/wiki/ASCII
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}
String source = "WEDGEZ"
char letter = source.charAt(i);
shift=5;
for (int i=0;i<source.length();i++){
if (source.charAt(i) >=65 && source.charAt(i) <=90 )
letterMix =(char)(('D' + (letter - 'D' + shift) % 26));
}
Ok what I'm trying to do is take the string WEDGEZ, and shift each letter by 5, so W becomes B and E becomes J, etc. However I feel like there is some inconsistency with the numbers I'm using.
For the if statement, I'm using ASCII values, and for the
letterMix= statement, I'm using the numbers from 1-26 (I think). Well actually, the question is about that too:
What does
(char)(('D' + (letter - 'D' + shift) % 26)); return anyway? It returns a char right, but converted from an int. I found that statement online somewhere I didn't compose it entirely myself so what exactly does that statement return.
The general problem with this code is that for W it returns '/' and for Z it returns _, which I'm guessing means it's using the ASCII values. I really dont know how to approach this.
Edit: New code
for (int i=0;i<source.length();i++)
{
char letter = source.charAt(i);
letterMix=source.charAt(i);
if (source.charAt(i) >=65 && source.charAt(i) <=90 ){
letterMix=(char)('A' + ( ( (letter - 'A') + input ) % 26));
}
}
Well I'm not sure if this homework, so i'll be stingy with the Code.
You're Writing a Caesar Cipher with a shift of 5.
To address your Z -> _ problem...I'm Assuming you want all the letters to be changed into encoded letters (and not weird Symbols). The problem is ASCII values of A-Z lie between 65 and 90.
When coding Z (for eg), you end up adding 5 to it, which gives u the value 95 (_).
What you need to do is Wrap around the available alphabets. First isolate, the relative position of the character in the alphabets (ie A = 0, B = 1 ...) You Need to subtract 65 (which is ASCII of A. Add your Shift and then apply modulus 26. This will cause your value to wrap around.
eg, it your encoding Z, (ASCII=90), so relative position is 25 (= 90 - 65).
now, 25 + 5 = 30, but you need the value to be within 26. so you take modulus 26
so 30 % 26 is 4 which is E.
So here it is
char letter = message(i);
int relativePosition = letter - 'A'; // 0-25
int encode = (relativePosition + shift) % 26
char encodedChar = encode + 'A' // convert it back to ASCII.
So in one line,
char encodedChar = 'A' + ( ( (letter - 'A') + shift ) % 26)
Note, This will work only for upper case, if your planning to use lower case, you'll need some extra processing.
You can use Character.isUpperCase() to check for upper case.
You can try this code for convert ASCII values to Char
class Ascii {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
char ch=sc.next().charAt(0);
if(ch==' ') {
int in=ch;
System.out.println(in);
}
}
}