代码之家  ›  专栏  ›  技术社区  ›  Templeton Peck

Java中的多行字符串串联

  •  0
  • Templeton Peck  · 技术社区  · 10 年前

    我在寻求帮助。在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 回复  |  直到 10 年前
        1
  •  1
  •   Remo Liechti    10 年前

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

    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);
        }
    }
    
        2
  •  1
  •   halfbit    10 年前

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

    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);
    }
    
        3
  •  0
  •   Bubletan    10 年前

    不那么漂亮,但很有用:

    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();
    
        4
  •  0
  •   sashaaero    10 年前

    我也在这里;)

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