【问题标题】:Merge two string with new line用新行合并两个字符串
【发布时间】:2013-12-22 14:52:21
【问题描述】:

目前,我有两个字符串

 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"

我该怎么办?

【问题讨论】:

  • strMerge= str1+str2??请明确您需要合并的依据。
  • 你的合并有什么规则吗?
  • 您的示例是无效的 Java。字符串文字必须在它们开始的行结束之前终止。

标签: java string merge newline


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2019-06-29
    • 2021-04-25
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多