Java中的多行字符串连接

时间:2015-03-28 20:22:02

标签: java string printing concat

我正在寻求帮助。在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类,但经过一些研究,我没有找到符合我需要的东西。

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

请参阅下面的示例,应该是自我解释。

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);
    }
}

答案 1 :(得分:0)

不太好但是有效:

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();

答案 2 :(得分:0)

我也在这里;)

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));
    }
}

答案 3 :(得分:0)

只是为了好玩,这是另一种使用溪流的解决方案,为两只以上的海龟准备并排显示:

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);
}