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

时间:2018-06-28 07:52:04

标签: java string word-wrap

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

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

我已经发送了一个包含换行符的句子,所以我希望此功能不要仅将现有换行符算作字符,而要在达到换行符时重置计数。

例如,我向该函数发送以下消息:“先民权法人化,阿维斯人永久化的事工,少数派的无产阶级权益。\ n法雷第3个月法令,未执行过执行权seraadresséau titulaire。”

它将字符“ \ n”作为字符进行计数,因此它会比应有的情况更早地剪切下一个短语。

2 个答案:

答案 0 :(得分:0)

您可能正在寻找下面的代码:

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

答案 1 :(得分:0)

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

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