Relating to this question: ROT-13 function in java?
What would be the code to decode rot13 in java?
Do I simply reverse the signs?
Below is the code for encoding a String into rot13:
public class Rot13 {
public static void main(String[] args) {
String s = args[0];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'N' && c <= 'Z') c -= 13;
System.out.print(c);
}
System.out.println();
}
}
You don't reverse the signs. The decoding method is identical to the encoding method.
For example : 'a' is encoded to 'n'. If you "encode" the 'n', it is decoded back to 'a'.
Because there are 26 letters (2×13) in the basic Latin alphabet, ROT13 is its own inverse; that is, to undo ROT13, the same algorithm is applied, so the same action can be used for encoding and decoding. The algorithm provides virtually no cryptographic security, and is often cited as a canonical example of weak encryption
The wikipedia article explains it pretty well
Related
I am quite at a loss here, i am to create a java programm which takes a String and decodes/encodes the string with n.(It adds n to the chars of the string like n=3 a=c) I buitl the "shell" which takes the user to the action he would like the programm to perform, then i dont get how to encode/decode the string with the key, it has to consider upper/lowercase and ignore special symbols like )/!/&"$;:.,, there has to be something with "for" and a chararray which i never worked with before and do not understand...
All help appreciated!
heres the code so far! https://gist.github.com/fabiomim/070d1daeee4b604db720adf7c7dff240
(ignore the little rant in fachklasse)
Some hints:
you can get the characters by using the charAt(int) or toCharArray() methods of String:
String string = ...
char ch = string.charAt(i);
// or
char[] characters = string.toCharArray();
char ch = characters[i];
A char is a Integral Type, that is, an integer type and you can do arithmetic with it, like comparison, addition, subtraction:
char ch = ...
if (ch >= 'a' && ch <= 'z') {
// do something it the char is between 'a' and 'z'
ch += 3; // 'a' will become 'd', 'z' will be '}'!!!!
if (ch > 'z') {
// handle overflow like subtracting 'z'+1 - 'a'
}
}
To create a String from the char array, you can use:
String result = new String(characters);
Note that a char is not an int, you need a cast to assign it to a char variable:
ch = ch + 3; // ERROR since "ch + 3" is an int
ch = ch + 'a'; // ERROR the result of + is still an int!
ch = (char) (ch + 3);
ch = (char) (ch + 'a');
What I have so far
public String toUpperCase(String str)
{
int strLength = str.length();
String word = "";
while (strLength > 0)
{
char newStr = str.charAt(strLength);
Character.toUpperCase(newStr);
Character.toString(newStr);
word += newStr;
strLength--;
}
return word;
}
I'm completely lost and my code is probably illogical. Some help would be appreciated
To change string into uppercase without using toUpperCase(), then check below code.
if(ch>96 && ch<123)
{
ch=ch-32;
System.out.print( (char) ch);
}
check char small letter or not , if small then subtract it from 32
The Character.toUpperCase() function returns a character. You have to hold that value in a char literal.
Plus, you should begin the loop at strLength - 1 otherwise it'll throw a StringIndexOutOfBounds error. And, you should iterate till the index 0. At present, you iterate from strLength till 1.
Lastly, since you are iterating in the opposite direction, you should take care of the way you append the characters.
public String toUpperCase(String str)
{
int strLength = str.length();
String word = "";
while (--strLength >= 0)
{
char newChar = str.charAt(strLength);
newChar = Character.toUpperCase(newChar);
word = newChar + word; //appending in reverse order
}
return word;
}
NOTE
Since you are asked to write the function considering that the function doesn't exist, it would be less ironical to NOT use the Character.toUpperCase() method. Even I have used it. In that case, you can take a look at #Sam's suggestion. The above code will then have this modification:
char newChar = str.charAt(strLength);
if((int)newChar > 96 && (int)newChar < 123)
newChar = newChar - 32;
//the if statement is the replacement of the Character.toUpperCase()
//function call
You should take a look at the ASCII table.
char are integer, 'A' to 'Z' is 65 to 90 and 'a' to 'z' is 97 to 122.
So if you have a char between 'a' and 'z' you want to substract the difference betwin 'A' and 'a' to your char.
'a' - ('a' - 'A') = 'A'
'c' - ('a' - 'A') = 'C'
So you need to iterate on your string and do your math on each character.
public static char myUpper(char c){
if (c >= 'a' || c <= 'z'){
c = (char) (c - ('a' - 'A'));
}
return c;
}
Personally this is what I would do.
String newsentence =""; String question="HeLlo";
String caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCase = "abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<caps.length();i++) {
for(int j=0;j<caps.length();j++) {
if(question.equals(lowerCase.subString(j,j+1)){ newsentence+= (caps.subString(i,i+1); }
}} System.out.print(newsentence);
This is what I would do.
I'm trying to implement a basic Caesar Shift Cipher for Java to shift all the letters by 13. Here's my code so far.
public static String cipher(String sentence){
String s = "";
for(int i = 0; i < sentence.length(); i++){
char c = (char)(sentence.charAt(i) + 13);
if (c > 'z')
s += (char)(sentence.charAt(i) - 13);
else
s += (char)(sentence.charAt(i) + 13);
}
return s;
}
However, the program also changes the values of numbers and special characters and I don't want that.
String sentence = "abc123";
returns "nop>?#"
Is there a simple way to avoid the special characters and only focus on letters?
Edit: I should mention I want to keep all the other bits. So "abc123" would return "nop123".
In the following example I encrypt just the letters (more precisely A-Z and a-z) and added the possibility to use any offset:
public static String cipher(String sentence, int offset) {
String s = "";
for(int i = 0; i < sentence.length(); i++) {
char c = (char)(sentence.charAt(i));
if (c >= 'A' && c <= 'Z') {
s += (char)((c - 'A' + offset) % 26 + 'A');
} else if (c >= 'a' && c <= 'z') {
s += (char)((c - 'a' + offset) % 26 + 'a');
} else {
s += c;
}
}
return s;
}
Here some examples:
cipher("abcABCxyzXYZ123", 1) // output: "bcdBCDyzaYZA123"
cipher("abcABCxyzXYZ123", 2) // output: "cdeCDEzabZAB123"
cipher("abcABCxyzXYZ123", 13) // output: "nopNOPklmKLM123"
Note: Due to your code, I assumed that you just want to handle/encrypt the "ordinary" 26 letters. Which means letters like e.g. the german 'ü' (Character.isLetter('ü') will return true) remain unencrypted.
Problem is that you add 13 as a fixed number, and that will for some letters (in second half of alphabet mostly and digits) produce characters that aren't letters.
You could solve this by using array of letters and shifting through those characters. (similar for digits) So something like this
List<Character> chars = ... // list all characters, separate lists for upper/lower case
char c = chars.get((chars.indexOf(sentence.charAt(i)) + 13)%chars.size());
I'm really loosing my hair over this one. Im making a (simple) encryption program.
Its supposed to take the char make it to an int, add 13 and convert back to a char. Then its supposed to do the same in reverse order. But my only outprint is two blank lines? I know the problem is when I convert back to letters for when I print x everything works. The part I've commented out was something I tried, and while I got an output endtwo was newer like the original text. Also I have to do this in modul 26.
String str = ("helloworld");
String end ="";
String endtwo ="";
for(int i = 0; i < str.length(); i++){
int x = str.charAt(i);
x = ((char)((x+13)%26));
char u =(char)x;
end += u;
//end += ((char)(str.charAt(i)+13));
}
for(int i = 0; i < str.length(); i++){
int x = str.charAt(i);
x = ((char)((x-13)%26));
char u =(char)x;
endtwo += u;
//endtwo += ((char)(str.charAt(i)-13));
}
In Java a char is an integer. Notice that the line
int x = str.charAt(i);
returns an integer which represents the character at the ith location in the String. So what is the value of the integer? You can look up the ASCII table for the letters of the alphabet. You will see that lower case h is 104 in decimal. So you then add 13 to this value so
104 + 13 = 117
You then proceed to mod by 26 which reduces the value to a range 0 to 25.
117 % 26 = 13
Decimal 13 in the ASCII table represents the carriage return character.
Similarly, going the other way you are starting with the 13 and subtracting 13 giving 0 then 0 mod 26 is 0 so 0 is the null character in the ASCII table.
Therefore, rethink your strategy for the encryption algorithm. For example, to get a simple cyclic cipher you can subtract the lower case character 'a' from the character to be encoded.
x = x - 'a';
x = x + 13;
x = x % 26;
x = x + 'a';
This guarantees that you end up with a letter of the alphabet. But only lower case though. How would you modify this to cater for upper case as well?
Also think carefully about the decipher step at the end. Subtracting 13 does not necessarily give you the answer you expect. Hint: Try running the cipher text through the exact same process as the encryption and see what happens.
A very simple approach to implement the ROT13 encryption algorithm is to check in wich range of ASCCI codes is each character, then add 13 or sub 13 depending on the range:
String str = "helloworld";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c < 'N' || c >= 'a' && c < 'n') {
c += 13;
} else if (c >= 'N' && c <= 'Z' || c >= 'n' && c <= 'z') {
c -= 13;
}
}
I've got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don't want to write, if(string.startsWith("a")); all the way to I, it seems in efficient. Should I be using a loop of some sort?
You don't need regular expressions for this.
Try this, assuming you want uppercase only:
char c = string.charAt(0);
if (c >= 'A' && c <= 'I') { ... }
If you do want a regex solution however, you can use this (ideone):
if (string.matches("^[A-I].*$")) { ... }
if ( string.charAt(0) >= 'A' && string.charAt(0) <= 'I' )
{
}
should do it
How about this for brevity?
if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
// string starts with a character between 'A' and 'I' inclusive
}
Try
string.charAt(0) >= 'a' && string.charAt(0) <= 'j'
char c=string.toLowerCase().charAt(0);
if( c >= 'a' && c <= 'i' )
...
This makes it easy to extract it as a method:
public static boolean startsBetween(String s, char lowest, char highest) {
char c=s.charAt(0);
c=Character.toLowerCase(c); //thx refp
return c >= lowest && c <= highest;
}
which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.
if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )
should be the easiest version...