Skip to content
Advertisement

How to append in String Builder in java? [closed]

Suppose I have sentence in String X. How can I split each word in sentence and add a span tag for each word with class word and if the word matches with String y add class word selected?

Both X and y Are dynamic

String X = "The community is here to help you with specific coding, algorithm, or language problems."
String Y = "community, here"

I create a function and split into array , but i am not able to append to string builder

    private String setPType(String X , String Y){
       String[] elements = Y.split(",");
       String[] newElement = X.split(",");
        StringBuilder sb = new StringBuilder();
        sb.append("<p id="view">");
        sb.append("</p>");
        return sb.toString();
    }

My output should look like this

<p id="view"> 
<span class="word">The</span>
<span class="word selected">community</span> 
<span class="word">is</span> 
<span class="word selected">here</span> 
<span class="word">to</span>
<span class="word ">help</span>
</p>

Advertisement

Answer

I’d split x by space, stream it, wrap every word with its span, and then join it back. For the distinction between selected and non selected words, I’d split y, store the words in a Set (not strictly required, but should improve performance, especially on large inputs), and use that to check for the required class:

private static String setPType(String x , String y) {
    Set<String> classifier = new HashSet<>(Arrays.asList(y.split(", ")));

    return Arrays.stream(x.split(" "))
            .map(w -> {
                String cls = classifier.contains(w) ? "word selected" : "word";
                return String.format("<span class="%s">%s</span>", cls, w);
            })
            .collect(Collectors.joining("n", "<p id="view">n", "n</p>"));
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement