1

I know its very easy to split data in strings, but still i want guide to concate string, my data is in the format. In my string the data is in the above format

104
inNetStandardGuest
windowsGuest
uestToolsTooOld


121
slesGuest
guestToolsTooOld
20569355609

Expected Output:

104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609
0

5 Answers 5

5

It's simply splitting and combining strings.

StringBuilder out = new StringBuilder();
for (String set : data.split("\n\n\n")) {
    for (String line : set.split("\n")) {
        out.append(line).append(',');
    }
    out.setCharAt(out.length(), '\n');
}
System.out.println(out);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for use of StringBuilder, but you can also use out.setCharAt(out.length(), '\n'); (and remove deleteCharAt line)
If you used "\n\n+" for the outer pattern, any number of empty lines would separate two blocks.
True, but no reason to check for that if the data format is unchanging.
2

With Guava's Splitter and Joiner:

final Iterable<String> lines = Splitter.on("\n\n\n").split(input);
for (final String line : lines) {
  final Iterable<String> fields = Splitter.on("\n").split(line);
  final String joined = Joiner.on(",").join(fields);
}

Comments

1

How about this?

String s = "104\n" +
           "inNetStandardGuest\n" +
           "windowsGuest\n" +
           "uestToolsTooOld\n" +
           "\n" +
           "\n" +
           "121\n" +
           "slesGuest\n" +
           "guestToolsTooOld\n" +
           "20569355609\n";

System.out.println(s.replaceAll("(.)\\n","$1,")
                    .replaceAll(",,","\n")
                    .replaceAll(",\\n","\n"));

Probably not the most efficient way, though.

Comments

0

Buffered reader: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html

readLine() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine()

For example you read 4 lines

  string outputLine = line1 + "," + line2 + "," + line3 + "," + line4;

Then read 2 lines and skip it.

If you don't know how to implement it using my advices, you should read some basics tutorial.

Comments

0

Try this :

String str = "104\ninNetStandardGuest\nwindowsGuest\nuestToolsTooOld\n\n\n121\nslesGuest\nguestToolsTooOld\n20569355609";
str= str.replaceAll("\\s", ",").replaceAll(",,,", "\n");
System.out.println(str);

Output :

104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.