Hey guys, I have a problem, I have to take a text and depending if a boolean - split_words is true or false I have to parse the text on some lines splitting the words or leaving them whole.
for example, text is: This is the text I have to split.
and
split_words = true

0123456789
This is th
e text I h
ave to spl
it

split_words = false

0123456789
This is 
the text I
have to
split

the 0123456789 are just for guidelines.
I managed to do the part for split_words = true, I can seem to figure out to do it for split_words=false.

p.s.
it seems the text arrangement gets change when I post but I hope you get the ideea behind the split.

Dani AI

Generated

The problem splits into two simple cases. As hinted, a plain substring loop is the cleanest solution when split_words == true. When split_words == false use a greedy, word-aware line filler: accumulate words into the current line until the next word would overflow, then emit the line and start a new one. The implementation below handles existing newlines (treats each paragraph separately) and breaks a single word that is longer than the target width.

public static String wrapText(String text, int width, boolean splitWords) {
    if (text == null) return "";
    if (width <= 0) throw new IllegalArgumentException("width must be > 0");

    StringBuilder out = new StringBuilder();
    if (splitWords) {
        for (int i = 0; i < text.length(); i += width) {
            int end = Math.min(i + width, text.length());
            out.append(text.substring(i, end));
            if (end < text.length()) out.append('\n');
        }
        return out.toString();
    }

    String[] paragraphs = text.split("\\r?\\n", -1);
    for (int p = 0; p < paragraphs.length; p++) {
        if (p > 0) out.append('\n');
        String para = paragraphs[p];
        if (para.length() == 0) continue;

        String[] words = para.split("\\s+");
        StringBuilder line = new StringBuilder();
        for (String w : words) {
            if (line.length() == 0) {
                if (w.length() <= width) line.append(w);
                else {
                    int s = 0;
                    while (s < w.length()) {
                        int e = Math.min(s + width, w.length());
                        out.append(w.substring(s, e));
                        s = e;
                        if (s < w.length()) out.append('\n');
                    }
                }
            } else if (line.length() + 1 + w.length() <= width) {
                line.append(' ').append(w);
            } else {
                out.append(line).append('\n');
                line.setLength(0);
                if (w.length() <= width) line.append(w);
                else {
                    int s = 0;
                    while (s < w.length()) {
                        int e = Math.min(s + width, w.length());
                        out.append(w.substring(s, e));
                        s = e;
                        if (s < w.length()) out.append('\n');
                    }
                }
            }
        }
        if (line.length() > 0) out.append(line);
    }
    return out.toString();
}

Notes and trade-offs: this collapses runs of whitespace to single spaces inside paragraphs (useful for typical wrapping); if exact whitespace preservation is required, replace the split-based tokenization with a manual scan. The method is linear-time in the input size and uses StringBuilder to avoid repeated string concatenation. This approach complements the brief hints already given in the thread and provides a compact, production-ready routine for both modes.

Recommended Answers

All 2 Replies

Okay? For the first one a simple substr in a loop. In the second one a simple substr in a loop combined with charAt to determine the index.

Using those hints, give it a try and then post your code with a specific question.

Thank you for the idea, I finally managed to do it.
for split=true code is pretty intuitive, for false it took a little work but I managed to finish it.
I can't post the code yet because the homework is still active but if you don't mind I can pm you the code and you can give me feedback on how I can optimize it.

thanks again for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.