I am working on a requirement where I need to enclose the individual strings in a comma-separated string in double-quotes while leaving the empty strings.
Eg : The string the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog should be converted to "the","quick","brown",,,,,"fox","jumped",,,"over","the","lazy","dog"
I have this piece of code that works. But wondering whether there is a better way to do this. btw, I am on JDK 8.
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
//split the string
List<String> list = Arrays.asList(str.split(",", -1));
// add double quotes around each list item and collect it as a comma separated string
String strout = list.stream().collect(Collectors.joining("\",\"", "\"", "\""));
//replace two consecutive double quotes with a empty string
strout = strout.replaceAll("\"\"", "");
System.out.println(strout);
CodePudding user response:
You can use split
and use stream
:
public static String covert(String str) {
return Arrays.stream(str.split(","))
.map(s -> s.isEmpty() ? s : '"' s '"')
.collect(Collectors.joining(","));
}
Then:
String str = "the,quick,brown,,,,,fox,jumped,,,over,the,lazy,dog";
System.out.println(covert(str));
Output:
"the","quick","brown",,,,,"fox","jumped",,,"over","the","lazy","dog"