Ahmed Mahdi
Ahmed Mahdi

Reputation: 39

Replace letters in a string without space

My question is how I can change many letters in a string respectively? I mean every letter changed to another one for example change (A to G, B to H, C to X, D to Y, G to A) for example:

I did this but nothing happened

String test = "ACDGBBDDGG";
String outputText = test.replaceAll("ABCDG","GHXYA");

System.out.println(outputText);

The output should be

GXYAHHYYAA

Upvotes: 3

Views: 147

Answers (3)

JimW
JimW

Reputation: 186

If you're using Java 8:

String fromChars = "ABCDG";
String toChars = "GHXYA";
String test = "ACDGBBDDGG";

test.chars().forEach(ch->System.out.print(toChars.charAt(fromChars.indexOf(ch))));

You could alternatively collect the results and turn it into a String.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

One possible method is to add the char and it's replacement to a Map and then "map" between the two like

Map<Character, Character> map = new HashMap<>();
map.put('A', 'G');
map.put('B', 'H');
map.put('C', 'X');
map.put('D', 'Y');
map.put('G', 'A');

String test = "ACDGBBDDGG";
StringBuilder sb = new StringBuilder();
for (char c : test.toCharArray()) {
    char o = map.containsKey(c) ? map.get(c) : c;
    sb.append(o);
}
System.out.println(sb.toString());

Another possibility (although more complex in terms of run-time) would be to to use the corresponding character's index in a String like

String in = "ABCDG";
String out = "GHXYA";
String test = "ACDGBBDDGG";
StringBuilder sb = new StringBuilder();
for (char c : test.toCharArray()) {
    int i = in.indexOf(c);
    char o = (i > -1) ? out.charAt(i) : c;
    sb.append(o);
}
System.out.println(sb.toString());

Both output (the requested)

 GXYAHHYYAA

Upvotes: 4

Damon Smith
Damon Smith

Reputation: 1790

try outputText = test.replaceAll("A","G").replaceAll("B","H").replaceAll("C","X") etc.

Upvotes: 0

Related Questions