Java 用新行合并两个字符串
现在,我有两条绳子Java 用新行合并两个字符串,java,string,merge,newline,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 I
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"
我必须怎么做?希望您对新行使用
\n
(如果否,请将拆分设置为:str1.split([]+”
):
strMerge=str1+str2
??请明确您需要合并的依据。合并有什么规则吗?您的示例是无效的Java。字符串文字必须在其起始行的结尾之前终止。
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