简体   繁体   English

如何将段落分为多行60个字符

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

I'm new to Coding area I apologize if this Question might have asked previously. 我是编码领域的新手,对于这个问题以前可能曾经提出过,我深表歉意。 I'm Trying to Achieve like this . 我正在努力实现这样的目标。 Suppose i have a Paragraph or Line which is more than 64 characters like this I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 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

At 60th Character we have word noticed so it should be pushed to next line. 在第60个字符处,我们注意到了单词,因此应将其推到下一行。 Expected output. 预期的输出。

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

Could you please help me out how to achieve this. 您能帮我解决这个问题吗? I have used String Tokenizer and substr() but didnt worked. 我用过String Tokenizer和substr(),但是没有用。

Please give your Valuable Suggestions. 请提出您的宝贵建议。

Thanks. 谢谢。

A very simple solution: 一个非常简单的解决方案:

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

This code will ensure each line is strictly less than or equal to splitLen . 此代码将确保每行严格小于或等于splitLen Any words coming after will be moved to next line. 之后的所有单词将移至下一行。

You can adjust the line width using splitLen argument. 您可以使用splitLen参数调整线宽。 I have tried to cover couple of scenarios. 我试图介绍几种情况。 If anything missing, kindly point out. 如果缺少任何内容,请指出。

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