用新行合并两个字符串

时间:2013-12-22 14:52:22

标签: java string merge newline

目前,我有两个字符串

 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 个答案:

答案 0 :(得分: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