如何将段落字符串沿 LHS 附加到 RHS ,而不是默认的 TOP 附加到底部为Strings
。
我是说
String par1 = "this paragraph consists\n"+
"of five lines which include\n"+
"line one \n"+
"line two \n"+
"and line three";
String par2 = "this paragraph consists\n"+
"of six lines which include\n"+
"line one \n"+
"line two \n"+
"line three \n"+
"and line four";
String TopBottomMerge = par1 +"\n"+ par2;
这使得:
String TopBottomMerge = "
this paragraph consists
of five lines which include
line one
line two
and line three
this paragraph consists
of six lines which include
line one
line two
line three
and line four";
怎么可能有
String LhsRhsMerge = ???;
给出:
"this paragraph consists this paragraph consists
of five lines which include of six lines which include
line one line one
line two line two
and line three line three
line four"
答案 0 :(得分:4)
使用par1.split("\n")
和par2.split("\n")
创建两个数组,每个数组保存对应段落中的行。
然后您可以使用for
在索引i
上循环,从最长数组的长度的0开始遍历这些数组,并在每一步在索引i
处添加行。 / p>
答案 1 :(得分:0)
int indx = str.indexOf(" - ");
String a1 = str.substring(0, indx);
String a2 = str.substring(indx+3, str.length());
split()比indexOf()更加计算密集
答案 2 :(得分:0)
这是一种方法。基本上是上面Tugrul Ates所建议的方法,但是插入空格以设置行格式,以使右行对齐。
替代行,在左侧添加,然后根据需要添加空格,然后在右侧添加。
/**
* Merge the lines from these two Strings alternating left and right.
* @param leftString the left lines
* @param rightString the right lines
* @return the merged lines
*/
private String mergeLeftRight(String leftString, String rightString) {
StringBuilder sb = new StringBuilder();
String[] leftLines = leftString.split("\n");
int leftSize = maxLength(leftLines) + 4; // max length of lines in left string
String[] rightLines = rightString.split("\n");
int leftIndex = 0;
int rightIndex = 0;
while (leftIndex < leftLines.length && rightIndex < rightLines.length) {
if (leftIndex < leftLines.length) {
String leftLine = leftLines[leftIndex++];
sb.append(leftLine);
appendSpaces(sb, leftSize - leftLine.length());
}
if (rightIndex < rightLines.length) {
sb.append(rightLines[rightIndex++]);
}
sb.append("\n");
}
return sb.toString();
}
/**
* Append spaces to the StringBuilder.
* @param sb the StringBuilder
* @param count the number of spaces to append
*/
private void appendSpaces(StringBuilder sb, int count) {
for (int i = 0; i < count; i++) {
sb.append(" ");
}
}
/**
* Find the max length of the Strings in the array.
* @param lines the array of Strings
* @return the max length
*/
private int maxLength(String[] lines) {
int max = 0;
for (String line : lines) {
max = Math.max(max, line.length());
}
return max;
}
答案 3 :(得分:-2)
您可以使用“扫描器”从每个段落中读取一行。添加一些空格或制表符或其他内容,然后在第二段中添加Frome行。这样做的最大好处是您可以循环运行以达到相同的目标。