1

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);
user864309
  • 226
  • 2
  • 11
  • You can do this in one line with a regex: `String strout = str.replaceAll("(\\w+)", "\"$1\"");` source: [Re-add strings with qoutations](https://stackoverflow.com/q/37550074/16653700) - Mason Smith – Alias Cartellano Dec 08 '21 at 19:23
  • What you are doing can be safer/stronger if make use of encodeURI (https://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu) – ControlAltDel Dec 08 '21 at 19:25
  • `str.replaceAll("[^,]+", "\"$0\"")` – shmosel Dec 08 '21 at 19:49

1 Answers1

4

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"
Oboe
  • 2,643
  • 2
  • 9
  • 17
  • @Holger Maybe I don't understand your comment correctly, but if you prepend `.filter(s ->!s.isEmpty())` you remove the empty strings and you won't get the desired output (you won't get `,,,`). And if you use the original code `.collect(Collectors.joining("\",\"", "\"", "\""))` considering the empty strings you won't the desired output either (i.e. `,"","",` instead of `,,,`). Is there something I'm missing? – Oboe Dec 09 '21 at 14:18
  • 1
    No, that’s a perfect explanation. With these considerations, there still might be a stream solution avoiding multiple string concatenations, but it would be more complicated than yours. So, if it has to be a stream solution instead of e.g. the `replaceAll` variants posted in comments below the question, yours is straight-forward. – Holger Dec 10 '21 at 08:14