Skip to content
Advertisement

Merge lines that share a word-link

so I’m having a small problem in java. I have something like

JavaScript

So what the sentence should actually look like is

JavaScript

Therefore I’m looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in “Victor Fleming” case where Fleming is not the same with Gone, so a new sentence is starting. What I’ve written so far:

JavaScript

Advertisement

Answer

We can store the sentences in a String array, then loop through each one.

Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.

If it isn’t, then we append the StringBuilder’s value to the list, append the current element, and move on.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement