If I have a string like this
String names = {"lucy, john, frank"}
but I want the string to look like: {"lucy","john","frank"}
So I want to replace all commas with commas in double quotes ( ","
)
I have String newNames = names.replaceAll(",", "","");
But this doesn't work. What's wrong?
Escape double quotes in string literals.
String names = "{\"lucy,john,frank\"}";
String newNames = names.replace(",", "\",\"");
Also, using String.replace
is already enough for your purpose. String.replaceAll
is for regular expressions.
You need to escape the "
like \\"
do instead :
String newNames = names.replaceAll(",", "\",\"");
This function will do it for any string
public static String fun(String str) {
return str.replace(".", "\",\"");
}
If you were using PHP i would suggest explode()
and implode()
but in Java you can use String.split()
and String.join()
. So what you want to do is:
String names = {"lucy, john, frank"};
String splitted = names.split(", ");
Hope it helps!!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.