javastringcharsequence

How can I replace a char sequence to "\n"


I want to replace the string "pqtd" to "\n", and my code is:

String str = "this is my pqtd string";

if (str.contains("pqtd")) {
        str.replaceAll("pqtd", "\n");
}

But that doesn't go, if I change all the code, doing it in reverse (trying to replace "\n" to "pqtd") it goes, so I think the problem is that Java can not replace a char sequence to "\n", at least I don't know-how.


Solution

  • There are multiple problems:

    1. You check if your String contains "pqtd" but then try to replace "dtdpq" which doesn't appear anywhere in your String. I'm really not sure where that extra "d" and "q" are coming from.

    2. You are using the methode replaceAll which takes a regular expression as first argument. Since yu want to replace a literal String you don't need to use regular expressions and can just use the standard replace method.

    3. String are immutable and cannot be modified. Therefor all replace options will not modify the original String but instead return the modified String as a return value. You need to use that return value and assign your String to it if you wanr any changes in your String to happen at all.

    Fixing all these 3 problems:

    String str = "this is my pqtd string";
    
    if (str.contains("pqtd")) {
            str = str.replace("pqtd", "\n");
    }
        
    System.out.println(str);
    

    Which will produce the expected output of

    this is my
    string