0

At the moment, I have two string

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

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

I want to merge two string to create a string as follow:

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

How must I do?

3
  • strMerge= str1+str2?? Please be clear on what basis you need to merge. Commented Dec 22, 2013 at 14:53
  • ARe there any rules for your merge? Commented Dec 22, 2013 at 14:53
  • Your example is invalid Java. String literals must be terminated before the end of the line on which they start. Commented Dec 22, 2013 at 14:59

1 Answer 1

1

Hope you use \n for new line, (if no, set split as: 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());

Output:

In the morning
In the afternoon
              I have breakfast
              I have dinner
              After
              Before
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.