0

I have an array of 6 different strings. Right now I'm focused on replacing all letters in the first sentence of the array with different characters. For example all 'r' in the sentence would become 'i' and all 't' would become 'u'. The code I tried below only replaces the characters of the code I've written on the last line. (It replaces all 'p' with 'u' but ignores all of the code above)

How do I replace every character in the sentence?

public static void replaceString(String[] arr) {
    
    String s1 = arr[0];
    for (String i: arr) {
        String sentence1 = s1.toLowerCase().replace("a", "t");
        sentence1 = s1.toLowerCase().replace("r", "m");
        sentence1 = s1.toLowerCase().replace("e", "i");
        sentence1 = s1.toLowerCase().replace("s", "n");
        sentence1 = s1.toLowerCase().replace("p", "u");
        System.out.println(sentence1);
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 2
    You need to reuse the same `String` you've assigned on the first line.. I'm sure you'll find which one :) – Yassin Hajaj Mar 01 '21 at 22:37
  • 1
    why the loop? ... You iterate through all strings, but never use them? `i` is ignored at so many levels..and sentence printed so many times... – aran Mar 01 '21 at 22:41

4 Answers4

4

You need to reuse the returned String otherwise you always rewrite the whole sentence1. Remember the String is immutable.

String sentence1 = s1.toLowerCase().replace("a", "t");
sentence1 = sentence1.toLowerCase().replace("r", "m");
sentence1 = sentence1.toLowerCase().replace("e", "i");
sentence1 = sentence1.toLowerCase().replace("s", "n");
sentence1 = sentence1.toLowerCase().replace("p", "u");

... which can be rewritten to:

String sentence1 = s1.toLowerCase()
                     .replace("a", "t")
                     .replace("r", "m");
                     .replace("e", "I");
                     .replace("s", "n");
                     .replace("p", "u");
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

You may find StringUtils.replaceChars() a better approach:

sentence1 = StringUtils.replaceChars(s1.toLowerCase(), "aresp", "tminu");

Add Apache’s commons-lang3 library as a dependency.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • worth mentioning that this would need an additional dependency. probably not worth it just for this use case. – eis Mar 01 '21 at 22:43
  • apache.commons.lang3 - it's worth it. This is the answer. – aran Mar 01 '21 at 22:44
0

Strings are immutable. You can't modify them in place, you always have to create a new object.

Example:

String s1 = "";
String s2 = s1 + "foo";
String s3 = s2.replace("foo", "bar");

s1 and s2 won't change, because they never get reassigned. Though the values of these variables stays the same:

System.out.println(s1); // ""
System.out.println(s2); // "foo"
System.out.println(s3); // "bar"

If you want s1 to change, you need to reassign the new value to it:

String s1 = "";
s1 = s1 + "foo";
s1 = s1.replace("foo", "bar");

Now s1 will be "bar"

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
0

You could write a text replacer that replaces every character by reducing the string according to each entry in the Map. You can optimize the string replacement by manipulating a StringBuilder object instead of a plain String.

import java.util.*;
import java.util.stream.Collectors;

public class TextReplacer {
    private static final Map<String, String> replacements;
    private static final List<String> phrases;

    static {
        phrases = List.of("Hello World", "Do you like peppers?");
        replacements = new HashMap<String, String>() {{
            put("r", "m");
            put("e", "i");
            put("s", "n");
            put("p", "u");
        }};
    }

    public static void main(String[] args) {
        replaceAll(phrases, replacements).stream().forEach(System.out::println);
        replaceAllOptimized(phrases, replacements).stream().forEach(System.out::println);
    }

    public static String replace(String phrase, Map<String, String> replacements) {
        return replacements.entrySet().stream().reduce(phrase.toLowerCase(), (s, e) -> s.replace(e.getKey(), e.getValue()), (s1, s2) -> null);
    }

    public static List<String> replaceAll(List<String> phrases, Map<String, String> replacements) {
        return phrases.stream().map(s -> replace(s, replacements)).collect(Collectors.toList());
    }

    public static String replaceOptimized(String phrase, Map<String, String> replacements) {
        return replacements.entrySet().stream().reduce(new StringBuilder(phrase.toLowerCase()), (s, e) -> replaceAll(s, e.getKey(), e.getValue()), (s1, s2) -> null).toString();
    }

    public static List<String> replaceAllOptimized(List<String> phrases, Map<String, String> replacements) {
        return phrases.stream().map(s -> replaceOptimized(s, replacements)).collect(Collectors.toList());
    }

    public static StringBuilder replaceAll(StringBuilder builder, String from, String to) {
        int index = builder.indexOf(from);
        while (index != -1) {
            builder.replace(index, index + from.length(), to);
            index += to.length();
            index = builder.indexOf(from, index);
        }
        return builder;
    }
}

Output

hillo womld
do you liki uiuuimn?
hillo womld
do you liki uiuuimn?
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132