Shift character in Alphabet [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ROT-13 function in java?
I have to shift all char from a string 13 places in the alphabet
private static String encode(String line) {
char[] toEncode = line.toCharArray();
for (int i = 0; i < toEncode.length; i++) {
if (Character.isLetter(toEncode[i])) {
toEncode[i] += 13;
}
}
line = String.valueOf(toEncode);
return line;
}
The Problem is that for example 'z' get to a ?. How can I solve that?
Thx for help.

It is because next chars after 'z' is punctuation chars and so on. You can shift so that 'z' will be 'n' for example.
toEncode[i] = (toEncode[i] + 13 - (int)'a') % 26 + (int)'a';

System.out.println(('z'+ (char)13)); //output -135
System.out.println((char)('z'+ (char)13)); //output - ?

If the calculated char is greater than the last letter (z => 122 or Z => 90) just substract the value of the last letter from the calculated value. You find these numbers all over the internet, e.g. here.

Related

(char) (i + 'a') JAVA: what's happening here? [duplicate]

This question already has answers here:
Adding and subtracting chars, why does this work? [duplicate]
(4 answers)
Parentheses around data type?
(5 answers)
What does a 'int' in parenthesis mean when giving a value to an int?
(7 answers)
What is the purpose and meaning of (char)i or (int)i in java?
(3 answers)
Closed 2 years ago.
I encountered a similar piece of code:
public class print {
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.print((char) (i + 'a'));
}
}
}
If I run it, I get "abcdef".
My question regards this expression: (char) (i + 'a').
I kind of intuitively get what's going on, but I want a rigorous step-by-step explanation of how the computer translates it. As indicated in some answers, the char is simply a number displayed as a character. Fine, but what does this syntax with parentheses actually do? Is it a conversion? Can I use it for other types as well?
The ASCII value of a is 97.
When i = 0, i + 'a' = 0 + 97 => When cast into char, it will be a
When i = 1, i + 'a' = 1 + 97 => When cast into char, it will be b
When i = 2, i + 'a' = 2 + 97 => When cast into char, it will be c
...and so on
Java char is a 16-bit integral type. 'a' is the same as 97, which you can see with System.out.println((int) 'a'); - it follows that 98 is 'b' and so on across the entire ASCII table.
You can use char as an integer value and vise versa
Below code may help:
char aChar = 'a'; // a char
int aCharAscii = aChar; // 97
char bChar = 'a' + 1; // b char
int bCharAscii = aChar + 1; // 98

Get the Unicode from a Hexadecimal

I've been searching for a solution to my problem for days but can't get a spot-on answer when looking at previously answered questions/ blogs / tutorials etc. all over the internet.
My aim is to write a program which takes a decimal number as an input and then calculates the hexadecimal number and also prints the unicode-symbol of said hexadecimal number (\uXXXX).
My problem is I can't "convert" the hexadecimal number to unicode. (It has to be written in this format: \uXXXX)
Example:
Input:
122 (= Decimal)
Output:
Hexadecimal: 7A
Unicode: \u007A | Unicode Symbol: Latin small letter "z"
The only thing I've managed to do is print the unicode (\u007A), but I want the symbol ("z").
I thought if the unicode only has 4 numbers/letters, I would just need to "copy" the hexadecimal into the code and fill up the remaining places with 0's and it kinda worked, but as I said I need the symbol not the code. So I tried and tried, but I just couldn't get the symbol.
By my understanding, if you want the symbol you need to print it as a string.
But when trying it with a string I get the error "illegal unicode escape".
It's like you only can print pre-determined unicodes and not "random" ones generated on the spot in relation of your input.
I'm only a couple days into Java, so apologies if I have missed anything.
Thank you for reading.
My code:
int dec;
int quotient;
int rest;
int[]hex = new int[10];
char[]chars = new char[]{
'F',
'E',
'D',
'C',
'B',
'A'
};
String unicode;
// Input Number
System.out.println("Input decimal number:");
Scanner input = new Scanner(System.in);
dec = input.nextInt();
//
// "Converting to hexadecimal
quotient = dec / 16;
rest = dec % 16;
hex[0] = rest;
int j = 1;
while (quotient != 0) {
rest = quotient % 16;
quotient = quotient / 16;
hex[j] = rest;
j++;
}
//
/*if (j == 1) {
unicode = '\u000';
}
if (j == 2) {
unicode = '\u00';
}
if (j == 3) {
unicode = '\u0';
}*/
System.out.println("Your number: " + dec);
System.out.print("The corresponding Hexadecimal number: ");
for (int i = j - 1; i >= 0; i--) {
if (hex[i] > 9) {
if (j == 1) {
unicode = "\u000" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 2) {
unicode = "\u00" + String.valueOf(chars[16 - hex[i] - 1]);
}
if (j == 3) {
unicode = "\u0" + String.valueOf(chars[16 - hex[i] - 1]);
}
System.out.print(chars[16 - hex[i] - 1]);
} else {
if (j == 1) {
unicode = "\u000" + Character.valueOf[hex[i]);
}
if (j == 2) {
unicode = "\u00" + Character.valueOf(hex[i]);
}
if (j == 3) {
unicode = "\u0" + Character.valueOf(hex[i]);
}
System.out.print(hex[i]);
}
}
System.out.println();
System.out.print("Unicode: " + (unicode));
}
It's not an advanced code whatsoever, I wrote it exactly how I would calculate it on paper.
Dividing the number through 16 until I get a 0 and what remains while doing so is the hexadecimal equivalent.
So I put it in a while loop, since I would divide the number n-times until I got 0, the condition would be to repeat the division until the quotient equals zero.
While doing so the remains of each division would be the numbers/letters of my hexadecimal number, so I need them to be saved. I choose an integer array to do so. Rest (remains) = hex[j].
I also threw a variable in the called "j", so I would now how many times the division was repeated. So I could determine how long the hexadecimal is.
In the example it would 2 letters/numbers long (7A), so j = 2.
The variable would then be used to determine how many 0's I would need to fill up the unicode with.
If I have only 2 letters/numbers, it means there are 2 empty spots after \u, so we add two zeros, to get \u007A instead of \u7A.
Also the next if-command replaces any numbers higher than 9 with a character from the char array above. Basically just like you would do on paper.
I'm very sorry for this insanely long question.
U+007A is the 3 bytes int code pointer.
\u007A is the UTF-16 char.
A Unicode code pointer, symbol, sometimes is converted to two chars and then the hexadecimal numbers do not agree. Using code pointers hence is best. As UTF-16 is just an encoding scheme for two-bytes representation, where the surrogate pairs for 3 byte Unicode numbers do not contain / or such (high bit always 1).
int hex = 0x7A;
hex = Integer.parseUnsignedInt("007A", 16);
char ch = (char) hex;
String stringWith1CodePoint = new String(new int[] { hex }, 0, 1);
int[] codePoints = stringWith1CodePoint.codePoints().toArray();
String s = "𝄞"; // U+1D11E = "\uD834\uDD1E"
You can simply use System.out.printf or String.format to do what you want.
Example:
int decimal = 122;
System.out.printf("Hexadecimal: %X\n", decimal);
System.out.printf("Unicode: u%04X\n", decimal);
System.out.printf("Latin small letter: %c\n", (char)decimal);
Output:
Hexadecimal: 7A
Unicode: u007A
Latin small letter: z

What is "charAt(i) - 'a'" means in Trie structure? [duplicate]

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.

How to shift characters in an array left in Java? [duplicate]

This question already has answers here:
How do I shift array characters to the right in Java?
(2 answers)
Closed 5 years ago.
This is what I have right now:
class encoded{
public static void main(String[] args){
int shift = In.getInt();
String s1 = "bool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
System.out.print(c);
}
}
}
This code works to shift all characters in the string left by however much I want it to shift. The problem arises when, for example, I shift 'abc' 1 left, it returns '`ab'. What I want is for the characters to wrap back around to 'z' instead, so that the shifted 'abc' becomes 'zab' instead. How would I go about doing this? The characters need to always wrap back around to z when they're shifted left of 'a', and need to wrap back around to a when they're shifted right of 'z' (this would be done by changing "'a' - shift" to "'a' + shift".
Thanks so much in advance!
Not doing your homework for you, but giving you some hints:
char c = (char) (((ch[i] - 'a' - shift) % 26) + 'a');
You see, you are doing the shift operation unconditionally. Instead, read about using the if statement. You want to do your program different things, compared on the value of ch[i]. For some cases, just "shift", for others to replace values.
The problem is that the modulo operation can yield negative results.
In Java8 you can use Math.floorMod as an alternative:
class Main{
public static void main(String[] args){
int shift = 1;
String s1 = "abool";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
char c = (char) ((Math.floorMod((ch[i] - 'a' - shift), 26)) + 'a');
System.out.print(c);
}
}
}
An alternative would be to use char c = (char) ( (((ch[i] - 'a' - shift) % 26) + 26) % 26 + 'a');

Conversion from ASCII values to Char

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);
}
}
}

Categories

Resources