Automatic and manual text wrapping in Java

76 Views Asked by At

I need as the title says to wrap a text (a String) in Java in both, automatic and manual mode. For automatic mode I use the "word-wrap" library that wrap the text with a max-length characters, but I need also to add a manual mode, like for example with the key "/". Can someone help me please?

I have tried to have a String like "this is an example string/I need to wrap" and also if I use a for loop to split the strings the word wrap, that is executed before. This is an example:

That is an example I need to fix /a example test.

Say the manual wrap key is "/" and the max characters are 35. The result will be:

That is an example I need to fix
a example test.

But here how is it:

That is an example I need to fix
a
example test
1

There are 1 best solutions below

2
Grinding For Reputation On BEST ANSWER

Here's a method that demonstrates what you want.

public static final String wrap(String toWrap, String wrapKey, int maxLineLength) {
    String string = new String();
    String[] words = toWrap.split(" ");

    int currentLineLength = 0;
    for (String word : words) {

        // Manual warping
        if(word.contains(wrapKey)) {
            while(word.contains(wrapKey)) 
                word = word.replaceFirst(wrapKey, "\n");
            
            string += (word + " ");
            currentLineLength = 0;
                
            continue; // Avoid auto-wrapping
        }
        // Auto warping
        if(currentLineLength + word.length() + 1 <= maxLineLength) {
            string += (word + " ");
            currentLineLength += word.length() + 1;
        }
        else {
            string += ("\n" + word + " ");
            currentLineLength = word.length() + 1;
        }
    }

    return string.trim();
}

And using it like so

String example = "That is an example I need to fix /a example test.";
        
System.out.println(wrap(example, "/", 35));

You should get

That is an example I need to fix 
a example test.

Alternatively your could use the ApacheCommon's WordUtils#wrap method