I am writing a cryptography program that converts the ciphertext to plaintext. By the letter's frequency, I manually crack all the cipher's letters to plaintext, and there is no patterns, so I need to write a loop that contains 26 times, to convert every single letter in the string to another letter.
My first try is using the replace statement in java,
which will be like this
str=str.replaceAll("A","E");
The question is, for instance, I input a string like this abc
and my key will be like this "replace a with c, replace b with p, replace c with q".
The output I want should be cpq, but the output I got is qpq.
Which means I want it be like one time convert.
So I am trying to use the loop, using the if
The way I am doing it is:
for (i=1;i<string.length;i++)
if (char[i]=="a")
char [i] ="b";
The error tells me that I can't convert string to char.
And also, I want to ask if I put the other 25 if statements inside this statement or pararall them?
To answer the second part of your question: I would not add 25 single if statements in your loop but instead use a Map<Character, Character> to store your replacements.
A complete solution could look like this:
public static void main(String[] args) {
Map<Character, Character> replacements = new HashMap<>();
replacements.put('a', 'c');
replacements.put('b', 'p');
replacements.put('c', 'q');
String input = "abcd";
StringBuilder output = new StringBuilder();
for (Character c : input.toCharArray()) {
output.append(replacements.getOrDefault(c, c));
}
System.out.println(output.toString());
}
This will keep characters you don't have a replacement for. Output:
cpqd
You can solve this as :
String str = "abc";
char [] ch = str.toCharArray();
for(int i=0; i<str.length(); i++){
if('a'==str.charAt(i)){
ch[i] = 'c';
}
if('b'==str.charAt(i)){
ch[i] = 'p';
}
if('c'==str.charAt(i)){
ch[i] = 'q';
}
}
System.out.println(String.valueOf(ch));
You can't convert a String to a char. So you need to either use all Strings or all chars. Instead of using the double quotes for String you could use the single quotes for char like this:
char[i]=='b'
and
char[i] = 'b';
Also instead of using a long if/else statement you could either use a switch statement, or even better you could create and use a Map to store the conversions in key/value pairs.
Related
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
okay.
this is my first post here and I'm kind of new to java
so my question is simple :
is there any instruction in java that remove special characters from a string ?
my string should be only letters
so when the user enters a spacebar or a point or whatever that isn't a letter
it should be removed or ignored
well my idea was about making an array of characters and shift letters to the left each time there is something that isn't a letter
so I wrote this code knowing that x is my string
char h[]=new char [d];
for (int f=0;f<l;f++)
{
h[f]=x.charAt(f);
}
int ii=0;
while (ii<l)
{
if(h[ii]==' '||h[ii]==','||h[ii]=='-'||h[ii]=='\\'||h[ii]=='('||h[ii]==')'||h[ii]=='_'||h[ii]=='\''||h[ii]=='/'||h[ii]==';'||h[ii]=='!'||h[ii]=='*'||h[ii]=='.')
{
for(int m=ii;m<l-1;m++)
{
h[m]=h[m+1];
}
d=d-1;
ii--;
}
ii++;
}
well this works it removes the special char but I can't include all the exceptions in the condition I wonder if there is something easier :)
As others have said Strings in Java are immutable.
One way to catch all characters you do not want is to only allow the ones you want:
final String input = "some string . ";
final StringBuffer sb = new StringBuffer();
final String permittedCharacters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (char c : input.toCharArray()){
if (permittedCharacters.indexOf(c)>=0){
sb.append(c);
}
}
final String endString = sb.toString();
Short answer - No, String is immutable. But you can use StringBuffer instead. This c ass contains deleteCharAt(int) method, that can be useful.
I have two Strings and a Json response :
InputString = "ab";
OutputString = "";
Json(example, not real one): Array(From:a,to:bhduh - From:b, to:eiaja).
*Json isn't a real response, it has 2 records for this example .
What i want to do is to replace a with bhduh and b with eiaja, I have a JSON loop which tell me to what i should replace, and i need to do it inside that loop, So here's what i tried :
InputString = InputString.replace(From,To);
Output
eiajahduheiaja
Expected Output
bhduheiaja
This's happening because in the first loop, it's changing a, and in the second loop, there's two b, the b in bhduh and b in the normal String.
The loop times depend on letters count, so sometimes it can be 5 or 6, depending on the server Json response.
What i want is to have the Expected Output, any ideas ?
It is unclear what JSON you have, but I'm guessing your problem is that you are replacing a with bhduh, (which contains a b), then you try to replace b with some other stuff. Obviously that isn't correct.
You need to loop over your initial input, then append your replacements to some other string, not replace upon your input.
For example, using a HashMap
public static void main (String[] args) throws java.lang.Exception
{
String input = "ab";
HashMap<Character, String> replacements = new HashMap<Character, String>() {{
put('a', "bhduh");
put('b', "eiaja");
}};
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
String rep = replacements.get(c);
if (rep != null) {
sb.append(rep);
}
}
System.out.println(sb.toString());
}
Example
If you replace all the original a's with some special character like - and all the original b's with another special character like *
you should then be able to replace the special characters with the desired phrase.
Something like:
String str = "ab";
str =str.replace("a", "-");
str =str.replace("b", "*");
str =str.replace("-", "bhduh");
str =str.replace("*","eiaja");
System.out.println(str);
very likely not the best solution but possibly a working one for now.
I would make a simple code in java to replace the letter 'z' by letter 'y' >>> here are the code
String s= "generalization";
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='z') s.charAt(i)='y';
The compiler return to me an error >>> why?
Strings are immutable. You can use a simple character array and alter the characters at the corresponding indices
Something like this perhaps:
String s = "Generalization";
char[] sChars = s.toCharArray();
for (int i = 0; i < sChars.length; i++) {
if (sChars[i] == 'z') {
sChars[i] = 'y';
}
}
s = String.copyValueOf(sChars);
System.out.println(s);
Prints out: Generaliyation
Or like suggested in another answer, in this sort of cases there is something called Regular expressions aka regex, with this the same thing is also accomplished by writing:
String s = "Generalization";
s = s.replace("z", "y");
System.out.println(s);
This also prints out: Generaliyation.
You can use the method replaceAll of the String class.
String s = "generalization";
s = s.replaceAll("[z]", "y");
Be careful, the first argument is a regex!
I'm trying to split some user input. The input is of the form a1 b2 c3 d4.
For each input (eg; a1), how do I split it into 'a' and '1'?
I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible?
Thanks.
You could use String#substring()
String a1 = "a1"
String firstLetterStr = a1.substring(0,1);
String secondLetterStr = a1.substirng(1,a1.length());
Similarly,
String c31 = "c31"
String firstLetterStr = c31.substring(0,1);
String secondLetterStr = c31.substirng(1,c31.length());
If you want to split the string generically (rather than trying to count characters per the other answers), you can still use String.split(), but you have to utilize regular expressions. (Note: This answer will work when you have strings like a1, a2, aaa333, etc.)
String ALPHA = "\p{Alpha}";
String NUMERIC = "\d";
String test1 = "a1";
String test2 = "aa22";
ArrayList<String> alpha = new ArrayList();
ArrayList<String> numeric = new ArrayList();
alpha.add(test1.split(ALPHA));
numeric.add(test1.split(NUMERIC));
alpha.add(test2.split(ALPHA));
numeric.add(test2.split(NUMERIC));
At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.)
it really depends how you're going to use the data afterwards, but besides split("") or accessing individual characters by index, one other way to split into individual character is toCharArray() -- which just breaks the string into an array of characters...
Yes, it is possible, you can use split("");
After you split user input into individual tokens using split(" "), you can split each token into characters using split("") (using the empty string as the delimiter).
Split on space into an array of Strings, then pull the individual characters with String.charAt(0) and String.charAt(1)
I would recommend just iterating over the characters in threes.
for(int i = 0; i < str.length(); i += 3) {
char theLetter = str.charAt(i);
char theNumber = str.charAt(i + 1);
// Do something
}
Edit: if it can be more than one letter or digit, use regular expressions:
([a-z]+)(\d+)
Information: http://www.regular-expressions.info/java.html