Search code examples
javareplaceall

How to introduce line break in a string whenever keyword occurs in java?


Objective: prefix each keyword with new line in a string

code snippet:

String [] keys = {"Status:","Active:","Priority:"};
text="Status:   Open    Active: Yes Priority:   None";
System.out.println("Before: "+text);
for(int k = 0; k<keys.length; k++){
text = text.replaceAll(keys[k], "\r\n"+keys[k]);
}
System.out.println("After: "+text);

Expected Output:

[new line]
Status: Open    
Active: Yes 
Priority:   None

Actual Output:

[new line]
Status: Open    Active: Yes Priority:   None

Update: the text is copied from web page with charset utf-8, pasted in notepad and saved with encoding utf-8. the text read by the program and unable to process. the same string has been pasted, I think encoding is not preserved.

Please help me resolving the issue.


Solution

  • The text contains \r\n but the way it is displayed does not show them.

    System.out.println print all on a single line, and at the end, this method insert a new line character.

    If you want to print out the modified text only for debug purpose, you can do this:

    System.out.println("After: " + text.replaceAll("\r\n", "\\r\\n");
    

    It will print out the text with visibles \r\n.