Java 中的多行字符串连接
Multiline strings concatenation in Java
我正在寻求帮助。在 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 class 和 StringBuilder class 但是经过一些研究,我没有找到符合我需要的东西。
在此先感谢您的帮助。
看我下面的例子,应该是自我解释。
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);
}
}
不是很漂亮,但有效:
String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r\n";
String[] turtle1Lines = turtle1.split("\r\n");
String[] turtle2Lines = turtle2.split("\r\n");
StringBuilder sb = new StringBuilder();
int turtle1Width = 0;
for (int i = 0; i < 4; i++) {
if (turtle1Lines[i].length() > turtle1Width) {
turtle1Width = turtle1Lines[i].length();
}
}
for (int i = 0; i < 4; i++) {
sb.append(turtle1Lines[i]);
for (int j = turtle1Width - turtle1Lines[i].length(); j > 0; j--) {
sb.append(' ');
}
sb.append(turtle2Lines[i]);
sb.append("\r\n");
}
String turtles = sb.toString();
我也来了 ;)
public class Test {
static String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r".replace("\r", "");
static String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r".replace("\r", "");
public static int countRows(String string){
return string.length() - string.replace("\n", "").length() + 1;
}
public static int getMaxLength(String string){
int maxLength = 0;
int currentLength = 0;
char[] data = string.toCharArray();
for(Character c : data){
if(c != '\n'){
if(++currentLength > maxLength) {
maxLength = currentLength;
}
}else{
currentLength = 0;
}
}
return maxLength;
}
public static String[] toStringArray(String string){
int length = getMaxLength(string);
int rows = countRows(string);
String[] result = new String[rows];
int last = 0;
for(int i = 0; i < rows; i++){
int temp = string.indexOf("\n", last);
String str;
if(temp != -1) {
str = string.substring(last, temp);
}else{
str = string.substring(last);
}
while(str.length() < length){
str += " ";
}
result[i] = str;
last = temp + 1;
}
return result;
}
public static String concatMultilineStrings(String first, String second){
StringBuilder sb = new StringBuilder();
String[] arrayFirst = toStringArray(first);
String[] arraySecond = toStringArray(second);
if(arrayFirst.length != arraySecond.length){
System.exit(69);
}
for(int i = 0; i < arrayFirst.length; i++){
sb.append(arrayFirst[i]);
sb.append(arraySecond[i]);
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(concatMultilineStrings(turtle1, turtle2));
}
}
只是为了好玩,这是另一个使用流的解决方案,准备并排显示两只以上的海龟:
public static void main(String[] args) {
String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r";
// split lines into fragments
List<List<String>> fragments = Stream.of(turtle1, turtle2)
.map(x -> Stream.of(x.split("\r\n?|\n")).collect(Collectors.toList()))
.collect(Collectors.toList());
// make all lists same length by adding empty lines as needed
int lines = fragments.stream().mapToInt(List::size).max().orElse(0);
fragments.forEach(x -> x.addAll(Collections.nCopies(lines - x.size(), "")));
// pad all fragments to maximum width (per list)
List<List<String>> padded = fragments.stream().map(x -> {
int width = x.stream().mapToInt(String::length).max().orElse(0);
return x.stream().map(y -> String.format("%-" + width + "s", y)).collect(Collectors.toList());
}).collect(Collectors.toList());
// join corresponding fragments to result lines, and join result lines
String result = IntStream.range(0, lines)
.mapToObj(i -> padded.stream().map(x -> x.get(i)).collect(Collectors.joining()))
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(result);
}
我正在寻求帮助。在 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 class 和 StringBuilder class 但是经过一些研究,我没有找到符合我需要的东西。
在此先感谢您的帮助。
看我下面的例子,应该是自我解释。
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);
}
}
不是很漂亮,但有效:
String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r\n";
String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r\n";
String[] turtle1Lines = turtle1.split("\r\n");
String[] turtle2Lines = turtle2.split("\r\n");
StringBuilder sb = new StringBuilder();
int turtle1Width = 0;
for (int i = 0; i < 4; i++) {
if (turtle1Lines[i].length() > turtle1Width) {
turtle1Width = turtle1Lines[i].length();
}
}
for (int i = 0; i < 4; i++) {
sb.append(turtle1Lines[i]);
for (int j = turtle1Width - turtle1Lines[i].length(); j > 0; j--) {
sb.append(' ');
}
sb.append(turtle2Lines[i]);
sb.append("\r\n");
}
String turtles = sb.toString();
我也来了 ;)
public class Test {
static String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r".replace("\r", "");
static String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r".replace("\r", "");
public static int countRows(String string){
return string.length() - string.replace("\n", "").length() + 1;
}
public static int getMaxLength(String string){
int maxLength = 0;
int currentLength = 0;
char[] data = string.toCharArray();
for(Character c : data){
if(c != '\n'){
if(++currentLength > maxLength) {
maxLength = currentLength;
}
}else{
currentLength = 0;
}
}
return maxLength;
}
public static String[] toStringArray(String string){
int length = getMaxLength(string);
int rows = countRows(string);
String[] result = new String[rows];
int last = 0;
for(int i = 0; i < rows; i++){
int temp = string.indexOf("\n", last);
String str;
if(temp != -1) {
str = string.substring(last, temp);
}else{
str = string.substring(last);
}
while(str.length() < length){
str += " ";
}
result[i] = str;
last = temp + 1;
}
return result;
}
public static String concatMultilineStrings(String first, String second){
StringBuilder sb = new StringBuilder();
String[] arrayFirst = toStringArray(first);
String[] arraySecond = toStringArray(second);
if(arrayFirst.length != arraySecond.length){
System.exit(69);
}
for(int i = 0; i < arrayFirst.length; i++){
sb.append(arrayFirst[i]);
sb.append(arraySecond[i]);
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(concatMultilineStrings(turtle1, turtle2));
}
}
只是为了好玩,这是另一个使用流的解决方案,准备并排显示两只以上的海龟:
public static void main(String[] args) {
String turtle1 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r";
String turtle2 = " _\r\n .-./*)\r\n _/___\/\r\n U U\r";
// split lines into fragments
List<List<String>> fragments = Stream.of(turtle1, turtle2)
.map(x -> Stream.of(x.split("\r\n?|\n")).collect(Collectors.toList()))
.collect(Collectors.toList());
// make all lists same length by adding empty lines as needed
int lines = fragments.stream().mapToInt(List::size).max().orElse(0);
fragments.forEach(x -> x.addAll(Collections.nCopies(lines - x.size(), "")));
// pad all fragments to maximum width (per list)
List<List<String>> padded = fragments.stream().map(x -> {
int width = x.stream().mapToInt(String::length).max().orElse(0);
return x.stream().map(y -> String.format("%-" + width + "s", y)).collect(Collectors.toList());
}).collect(Collectors.toList());
// join corresponding fragments to result lines, and join result lines
String result = IntStream.range(0, lines)
.mapToObj(i -> padded.stream().map(x -> x.get(i)).collect(Collectors.joining()))
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(result);
}