我知道在字符串中分割数据很容易,但我仍然需要指南来连接字符串, 我的数据是格式。在我的字符串中,数据采用上述格式
104
inNetStandardGuest
windowsGuest
uestToolsTooOld
121
slesGuest
guestToolsTooOld
20569355609
预期产出:
104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609
答案 0 :(得分:5)
它只是拆分和组合字符串。
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);
答案 1 :(得分:2)
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);
}
答案 2 :(得分:1)
这个怎么样?
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"));
可能不是最有效的方式。
答案 3 :(得分:0)
缓冲读者: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html
readLine()方法: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine()
例如,您阅读了4行
string outputLine = line1 + "," + line2 + "," + line3 + "," + line4;
然后阅读2行并跳过它。
如果你不知道如何使用我的建议来实现它,你应该阅读 一些基础教程。
答案 4 :(得分:0)
试试这个:
String str = "104\ninNetStandardGuest\nwindowsGuest\nuestToolsTooOld\n\n\n121\nslesGuest\nguestToolsTooOld\n20569355609";
str= str.replaceAll("\\s", ",").replaceAll(",,,", "\n");
System.out.println(str);
输出:
104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609