2013-12-22 46 views
0

目前,我有兩個字符串合併兩個字符串,新的生產線

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" 

我該怎麼辦呢?

+0

'strMerge = STR1 + str2' ??請明確您需要合併的基礎。 –

+0

ARe有沒有合併的規則? – smk

+0

你的例子是無效的Java。字符串文字必須在它們開始的行結束之前終止。 –

回答

0

希望您使用\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