簡體   English   中英

如何將段落分為多行60個字符

[英]How to frame Paragraph into multiple lines of 60 Characters

我是編碼領域的新手,對於這個問題以前可能曾經提出過,我深表歉意。 我正在努力實現這樣的目標。 假設我有一個這樣的段落或行,超過64個字符,而I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters

在第60個字符處,我們注意到了單詞,因此應將其推到下一行。 預期的輸出。

I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters

您能幫我解決這個問題嗎? 我用過String Tokenizer和substr(),但是沒有用。

請提出您的寶貴建議。

謝謝。

一個非常簡單的解決方案:

public String appendNewLine(String text, int max) {
    int count = 0;
    StringBuilder output = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);

            if (count >= max && c == ' ') {
                count = 0;
                output.append("\n");
            } else {
                output.append(c);    
            }
            count++;
        } 
    return output.toString();
}

此代碼將確保每行嚴格小於或等於splitLen 之后的所有單詞將移至下一行。

您可以使用splitLen參數調整線寬。 我試圖介紹幾種情況。 如果缺少任何內容,請指出。

public String splitString(String s, int splitLen){

    StringBuilder sb = new StringBuilder();
    int splitStart = 0;

    while(splitStart < s.length()){

        int splitEnd = splitStart + splitLen;
        splitEnd = splitEnd > s.length() ? s.length() : splitEnd;   // avoid overflow

        int spaceIndex = s.substring(splitStart, splitEnd)
                    .lastIndexOf(" ");

        // look for lasts space in line, except for last line
        if(spaceIndex != -1 && splitEnd != s.length()){
            splitEnd = splitStart + spaceIndex;
        }
        // else (no space in line), split word in two lines..

        sb.append(s.substring(splitStart, splitEnd))
            .append(System.lineSeparator());

        // if ends with space, skip space in next line
        splitStart = splitEnd + (spaceIndex != -1 ? 1 : 0); 
    }

    return(sb.toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM