【问题标题】:How do i format string with one space and 60 characters in every line?如何格式化每行一个空格和 60 个字符的字符串?
【发布时间】:2021-07-14 12:05:32
【问题描述】:

我试图解决这个问题,但遇到了小错误。 我必须用空格重新格式化此文本,并且每行的长度不得超过 60 个字符。

“Java 最初由 Sun Microsystems 的 James Gosling 开发(后来被 Oracle 收购),并于 1995 年作为 Sun Microsystems Java 平台的核心组件发布。”

这是我的代码:

static String text;
public String reformatLines(String text) {  
    if(text == null || text.isEmpty()); 
       return text;
}   
public static void main(String[] args) {        
    String text = "Java    was      originally developed   by    James   Gosling at Sun Microsystems (which has since been acquired by Oracle) and released in 1995 as a core component of Sun Microsystems' Java platform.";
    String str = text.replaceAll("[\n]{2,}", " ");
    int length = 60;
    String jump = new String();
    while(text.length()>length){
        int jp = str.lastIndexOf(" ", length);
        jump = jump.concat(str.substring(0, jp));
        jump = jump.concat("\n");
        str = str.substring(jp, str.length());
    }   
}   

}

其实我也不知道怎么办……

【问题讨论】:

标签: java


【解决方案1】:
text = text.replaceAll("\\s{2,}", " ").replaceAll("(.{1,60}).*", "$1");

会是一个快速的方法

【讨论】:

  • 好的,我已经运行了你的代码,在 sysout 中看起来像“Java 最初是由 Sun Micros 的 James Gosling 开发的”,仅此而已
  • 是的,因为您的问题标题包含>和 60 个字符
  • 练习是用下面的方法来格式化这个文本:得到没有空格的全文,每行的长度不能超过60个字符。也许我在这个问题的主题上做错了:?
  • 我是按照问题标题和你的代码中的字符串是一行的事实来的
  • 对不起...我对这个练习很感兴趣
【解决方案2】:

用一个空格替换空格

text.replaceAll("\\s+", " ");

【讨论】:

  • 13:40 java: 非法转义字符
  • 缺少额外的反斜杠。固定。
  • 可以分享一下测试对比失败的结果吗?
【解决方案3】:

如何在空白处拆分文本并通过插入单个空格和换行符来重建它以满足行长限制?

static String format(String text, int length)
{
    StringBuilder b = new StringBuilder();
    
    int curr = 0;
    for (String word : text.split("\\s+"))
    {
        int nextLen = curr + word.length();
        
        if(curr > 0) 
            nextLen += 1;       
        
        if (nextLen > length)
        {
            b.append(System.getProperty("line.separator"));
            curr = 0;
        }

        if (curr > 0)
        {
            b.append(" ");
            curr += 1;
        }

        b.append(word);
        curr += word.length();
    }
    b.append(System.getProperty("line.separator"));
    
    return b.toString();
}

测试:

String text = "Java    was      originally developed   by    James   Gosling at Sun Microsystems (which has since been acquired by Oracle) and released in 1995 as a core component of Sun Microsystems' Java platform.";
System.out.print(format(text, 60));

输出:

Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2017-06-02
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多