2. This question involves the TextCombiner class, which models a pair of strings that can be combined or wrapped within other strings. You will write the complete TextCombiner class, which contains a constructor and two methods.
TextCombiner objects are created by calls to a constructor with two parameters.
The first text segment to be stored (Precondition: The string is not null and has a length greater than 0)
The second text segment to be stored (Precondition: The string is not null and has a length greater than 0)
getCombinedText
Returns a string containing the two stored text segments combined according to specific rules.
If the last character of the first segment is equal to the first character of the second segment, the method returns the concatenation of the first segment and the substring of the second segment starting at index 1 (removing the duplicate character).
Otherwise, the method returns the concatenation of the first segment and the second segment.
The comparison of characters is case-sensitive.
A string representing the combined text.
insertInto
Returns a new string created by inserting the combined text into a wrapper string.
wrapper - a string into which the combined text will be inserted
The method first calls getCombinedText to obtain the combined string.
It calculates the insertion index as wrapper.length() / 2.
It returns a new string formed by the substring of wrapper from index 0 to the insertion index, followed by the combined string, followed by the rest of the wrapper.
The wrapper string with the combined text inserted in the middle.
Statement | Return Value | Explanation |
|---|---|---|
TextCombiner t1 = new TextCombiner("dog", "gone"); | t1 is initialized with "dog" and "gone". | |
t1.getCombinedText(); | "dogone" | The last letter of "dog" ('g') matches the first letter of "gone" ('g'). They are merged. |
t1.insertInto("1234"); | "12dogone34" | "dogone" is inserted into "1234" at index 2 (4 / 2). |
TextCombiner t2 = new TextCombiner("red", "car"); | t2 is initialized with "red" and "car". | |
t2.getCombinedText(); | "redcar" | The last letter of "red" ('d') does not match the first letter of "car" ('c'). They are concatenated normally. |
t2.insertInto("[]"); | "[redcar]" | "redcar" is inserted into "[]" at index 1 (2 / 2). |
Write the complete TextCombiner class. Your implementation must meet all specifications and conform to the examples shown in the table.