如何在函数中保留现有的换行符

How to keep existing line breaks in a function

我有一个函数,当句子长于给定数字时,可以在单词前插入换行符:

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;
    }
}

我已经发送了一个包含换行符的句子,所以我希望这个函数不要只将现有的换行符计为字符,而是在到达换行符时重置计数。

例如,我向函数发送以下内容:"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."

它将字符“\n”计为一个字符,因此它会比应有的时间更早地剪切下一个短语。

可能下面的代码就是您要找的:

public static String wrapString(String string, int charWrap)
{
int lastBreak = 0;
int nextBreak = charWrap;
if (string.length() > charWrap)
{
    String setString = "";
   int counter = 0; // create a counter to help you check each char if it is not a new line
    do {
        if(string.charAt(lastBreak+counter) == '\n' || 
        string.charAt(lastBreak+counter) == '\r') { 
        nextBreak = lastBreak + charWrap;
        setString += string.substring(lastBreak, nextBreak).trim() + "\n";
        lastBreak = nextBreak;
        counter = 0;// if it is a new line change counter back to zero
        }
        if(counter == charWrap) { // if counter has reached max range to split without finding any new line character, proceed with normal process of injecting new line)
         nextBreak = lastBreak+counter; 
        while (string.charAt(nextBreak) != ' ' && nextBreak > lastBreak)
        {
            nextBreak--;
        }
        if (nextBreak == lastBreak)
        {
            nextBreak = lastBreak + charWrap;
        }
        counter = 0;
        setString += string.substring(lastBreak, nextBreak).trim() + "\n";
        lastBreak = nextBreak;
        }
        counter ++;

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

您可以先从换行符中拆分句子,然后 运行 为每个字符串编写代码。最后连接所有的字符串。

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);