Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace letters by loop in java?

Tags:

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?

like image 457
Zecheng Li Avatar asked Sep 06 '25 20:09

Zecheng Li


1 Answers

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
like image 161
Marvin Avatar answered Sep 10 '25 12:09

Marvin