Java: Str_replace a character with a new line "\n"

25,975

Solution 1

text = text.replace(',', '\n');

Solution 2

With the replaceAll method:

text.replaceAll(",","\n");

Solution 3

Use this:

text = text.replace(", ", "\n");

NB: The first parameter is a comma followed by a space. It will replace the comma and the space following it with a new line. It looks much nicer this way, unless you wanted the spaces in the beginning.

Share:
25,975
user2421111
Author by

user2421111

Updated on July 29, 2022

Comments

  • user2421111
    user2421111 almost 2 years

    Here's the code:

    String text = "hello, my name, is john smith.";
    

    How do I make it into:

    String text = "hello\n my name\n is john smith.";
    

    Thanks!

  • Keppil
    Keppil almost 11 years
    You get the +1 for using replace() instead of replaceAll(), and reassigning to the text variable.
  • user2421111
    user2421111 almost 11 years
    Why do I get an error using speechmarks "", but it works using ' apostrophes? And it works, thank you. And why is replace better?
  • user2421111
    user2421111 almost 11 years
    On all the solutions people give me, why does it say: No suitable method found for replace(java.land.String,char) method java.lang........ is not applicable;
  • Djon
    Djon almost 11 years
    You probably tried replace(",",'\n') which is wrong.
  • Ravi K Thapliyal
    Ravi K Thapliyal almost 11 years
    @user2421111 call replace with single quotes to denote you're passing a character like replace(',', '\n')
  • Ravi K Thapliyal
    Ravi K Thapliyal almost 11 years
    @Keppil I up voted for the same. :)
  • Keppil
    Keppil almost 11 years
    @user2421111: replaceAll() uses regular expressions, which is unnecessary here, replace() does not.
  • user2421111
    user2421111 almost 11 years
    So, it seems to only work with " if I use String, ' for character? Am I right? Please confirm and say my username.
  • Ravi K Thapliyal
    Ravi K Thapliyal almost 11 years
    @user2421111 replace() is better because you just want to replace a character. replaceAll() would unnecessarily try to compile a regex out of your first parameter.
  • user2421111
    user2421111 almost 11 years
    Why do I have to use a speechmark?
  • Djon
    Djon almost 11 years
    @user2421111 Yes, '' delimits a char and "" a String, read this docs.oracle.com/javase/7/docs/api/java/lang/…
  • Kazenga
    Kazenga almost 11 years
    method replace want characters for input and with "," symbols you put string so if you want to write character you must use ','
  • Steve P.
    Steve P. almost 11 years
    You have to use "" because this you need to pass ", " as a String, since it can't be represented by a single character. There isn't a replace that takes a char and String, so you must also past the newline character as a String "\n"