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.
Author by
user2421111
Updated on July 29, 2022Comments
-
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 almost 11 yearsYou get the +1 for using
replace()
instead ofreplaceAll()
, and reassigning to thetext
variable. -
user2421111 almost 11 yearsWhy do I get an error using speechmarks "", but it works using ' apostrophes? And it works, thank you. And why is replace better?
-
user2421111 almost 11 yearsOn 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 almost 11 yearsYou probably tried
replace(",",'\n')
which is wrong. -
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 almost 11 years@Keppil I up voted for the same. :)
-
Keppil almost 11 years@user2421111:
replaceAll()
uses regular expressions, which is unnecessary here,replace()
does not. -
user2421111 almost 11 yearsSo, it seems to only work with " if I use String, ' for character? Am I right? Please confirm and say my username.
-
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 almost 11 yearsWhy do I have to use a speechmark?
-
Djon almost 11 years@user2421111 Yes, '' delimits a char and "" a String, read this docs.oracle.com/javase/7/docs/api/java/lang/…
-
Kazenga almost 11 yearsmethod replace want characters for input and with "," symbols you put string so if you want to write character you must use ','
-
Steve P. almost 11 yearsYou have to use
""
because this you need to pass", "
as aString
, since it can't be represented by a single character. There isn't areplace
that takes achar
andString
, so you must also past the newline character as a String"\n"