Search code examples
javastringword-wrap

How to keep existing line breaks in a function


I have a function that inserts a line break before a word when the sentence is longer than a given number :

public static String wrapString(String string, int charWrap)
{
    int lastBreak = 0;
    int nextBreak = charWrap;
    if (string.length() > charWrap)
    {
        String setString = "";
        do {
            while (string.charAt(nextBreak) != ' ' && nextBreak > lastBreak)
            {
                nextBreak--;
            }
            if (nextBreak == lastBreak)
            {
                nextBreak = lastBreak + charWrap;
            }
            setString += string.substring(lastBreak, nextBreak).trim() + "\n";
            lastBreak = nextBreak;
            nextBreak += charWrap;

        }
        while (nextBreak < string.length());
        setString += string.substring(lastBreak).trim();
        return setString;
    }
    else
    {
        return string;
    }
}

I send a sentence including line breaks already, so I would like this function not to count existing line breaks only as characters, but to reset the counting when it reaches a line break.

For example I send to the function the following : "En cas de paiement avant minuit, suivant la date d'apposition du présent avis, vous bénéficiez d'une minoration.\n Après le délai de 3 mois, un titre exécutoire sera adressé au titulaire."

It counts the char "\n" as a character so it cuts the next phrase earlier than it should.


Solution

  • You can first split sentences from line breaks and then run your code for each of the strings. Finally concatenate all of the strings.

    String para = "abc abc abc abc abc abc abc abc abc abc \n" +
                "abc abc abc abc abc abc abc abc abc abc ";
    
    String[] sentences = para.split("\n");
    String finalString = "";
    for (String s : sentences) {
        finalString = finalString + wrapString(s, 20).trim() + "\n";
    }
    
    System.out.println(finalString);