Zecheng Li
Zecheng Li

Reputation: 53

how to replace letters by loop in java?

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?

Upvotes: 4

Views: 13429

Answers (3)

Marvin
Marvin

Reputation: 14255

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

Upvotes: 4

Mohit Tyagi
Mohit Tyagi

Reputation: 2876

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

Upvotes: 4

jwils
jwils

Reputation: 525

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.

Upvotes: 2

Related Questions