【问题标题】:Multiline strings concatenation in JavaJava中的多行字符串连接
【发布时间】:2015-03-28 20:22:01
【问题描述】:

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

提前感谢您的帮助。

【问题讨论】:

  • 澄清一下,你想把turtle1的第一行和turtle2的第一行连接起来,以此类推...?
  • 是的。谢谢你帮助我
  • 为每个字符串拆分“/r/n”上的行,这将为您提供两个字符串数组,对于每个数组中的每个元素,将它们连接在一起,添加一个“/r/n “ 到最后。你可以使用 StringJoiner

标签: java string printing concat


【解决方案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);
    }
}

【讨论】:

  • 这是不正确的,因为您没有为不够长的行添加空格。
  • 非常感谢您的回答!
  • 布布坦,你是对的。我没看到那里有短的。使用格式化程序更新答案以解决此问题。
【解决方案2】:

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

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】:

    不是很漂亮,但很有效:

    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】:

      我也在;)

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

      【讨论】:

        猜你喜欢
        • 2012-08-28
        • 1970-01-01
        • 2011-04-02
        • 2016-03-21
        • 2015-09-18
        • 2019-04-12
        相关资源
        最近更新 更多