public class Test
{
public static void main(String[] args)
{
System.out.println(concatenateHorizontally("AAA\nBBB\nCCC", "111\n222\n333", "\n", " "));
System.out.println(concatenateHorizontally("AAA\nBBB", "111\n222\n333", "\n", " "));
System.out.println(concatenateHorizontally("AAA\nBBB\nCCC", "111\n222", "\n", " "));
}
private static String concatenateHorizontally(final String left, final String right, String br, String concat)
{
{
String[] lefts = left.split(br);
String[] rights = right.split(br);
int max = Math.max(lefts.length, rights.length);
StringBuilder sB = new StringBuilder();
for (int i = 0; i < max; i++)
{
if (i < lefts.length)
sB.append(lefts[i]).append(concat);
if (i < rights.length)
sB.append(rights[i]);
sB.append(br);
}
return sB.toString();
}
}
}
What is a good library for horizontally concatenating text using Java? [closed]
-
26-06-2023 - |
题
I have two strings
AAA
AAA
AAA
and
BBB
BBB
BBB
What I'm looking for is a method String concatenateHorizontally(String left, String right, String separator, options...)
that I can pass those strings to and receive a String
AAA BBB
AAA BBB
AAA BBB
I do this a lot in Vim (using blockwise visual mode) but couldn't find a library that allows to do it in Java code. I'm aware that for simple examples this is trivial to implement but I was hoping that someone has already solved this in a more generic way (e.g. with options to decide whether to replace or append, to insert at a fixed position or the line end, handling different newline characters, correct Unicode behavior etc.).
Can someone point me to such a library for horizontally concatenating text?
解决方案 2
其他提示
You can split by line returns and append alternately.
No code example because of "Easy Kill".
EDIT :
Implemented because of "Nice":
String concatenateHorizontally(final String left, final String right) {
String br = "\n";
String[] lefts = left.split(br);
String[] rights = right.split(br);
if(lefts.length!=rights.length)
throw new UnsupportedOperationException("This is where my time becomes money");
StringBuilder sB = new StringBuilder();
for (int i = 0; i < lefts.length; i++) {
sB.append(lefts[i]);
sB.append(rights[i]);
sB.append(br);
}
return sB.toString();
}
Try This :
class m
{
public static void main(String[] args)
{
String s="AAA"+"\n"+
"AAA"+"\n"+
"AAA"+"\n";
String s1="BBB"+"\n"+
"BBB"+"\n"+
"BBB"+"\n";
String[] gets=s.split("\n");
String[] gets1=s1.split("\n");
String concate="";
for(int i=0;i<3;i++)
{
concate=concate+gets[i]+"\t"+gets1[i]+"\n";
}
System.out.print(concate);
}
}
output:
AAA BBB
AAA BBB
AAA BBB