有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用新行合并两个字符串

现在,我有两条绳子

 String str1="In the morning
              I have breakfast
              After";

 String str2="In the afternoon
              I have dinner
              Before";

我想合并两个字符串以创建一个字符串,如下所示:

String strMerge="In the morning
                 In the afternoon
                 I have breakfast
                 I have dinner
                 After
                 Before"

我该怎么办


共 (1) 个答案

  1. # 1 楼答案

    希望您使用\n作为新行(如果没有,请将拆分设置为:str1.split("[ ]+")):

    String str1 = "In the morning\r\n" + 
                    "              I have breakfast\r\n" + 
                    "              After";
    
            String str2 = "In the afternoon\r\n" + 
                    "              I have dinner\r\n" + 
                    "              Before";         
    
            StringBuilder buff = new StringBuilder();           
    
            List<String> list1 = new ArrayList<String>(Arrays.asList(str1.split("\r\n")));
            List<String> list2 = new ArrayList<String>(Arrays.asList(str2.split("\r\n")));
    
            if(list1.size() == list2.size()){           
                for(int i = 0; i<list1.size(); i++){
                    buff.append(list1.get(i)).append("\r\n")
                        .append(list2.get(i)).append("\r\n");
                }           
            }
    
            System.out.print(buff.toString());
    

    输出:

    In the morning
    In the afternoon
                  I have breakfast
                  I have dinner
                  After
                  Before