我正在寻求帮助。在 Java 中连接多行字符串并在之后打印的最简单方法是什么?
例如:我有两个字符串:
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r";
我想在 Java Eclipse 控制台中得到这个结果:
_ _
.-./*) .-./*)
_/___\/ _/___\/
U U U U
我已经尝试了一些算法来将字符串分成不同的部分,然后重新连接它。但没有成功。 我知道有 StringBuffer 类和 StringBuilder 类,但经过一番研究,我没有找到符合我需要的东西。
预先感谢您的帮助。
最佳答案
请参阅下面的示例,应该是不言自明的。
public class Turtle {
private static final String returnpattern = "\r\n";
public static void main(String[] args) {
// the data to run through
String turtle1 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\\/\r\n U U\r\n";
// split the data into individual parts
String[] one = turtle1.split(returnpattern);
String[] two = turtle2.split(returnpattern);
// find out the longest String in data set one
int longestString = 0;
for (String s : one) {
if (longestString < s.length()) {
longestString = s.length();
}
}
// loop through parts and build new string
StringBuilder b = new StringBuilder();
for (int i = 0; i < one.length; i++) {
String stringTwo = String.format("%1$" + longestString + "s", two[i]); // left pad the dataset two to match
// length
b.append(one[i]).append(stringTwo).append(returnpattern);
}
// output
System.out.println(b);
}
}
关于java - Java中的多行字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322159/