将长字符串分成60个字符的长行,但不要弄断单词 [英] Divide long string into 60 character long lines but don't break words

查看:47
本文介绍了将长字符串分成60个字符的长行,但不要弄断单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须有一种更好的方法来做到这一点.我只想将长字符串分成60个字符行,但不打断单词.因此,它不必添加最多60个字符,而必须少于60个字符.

There has to be a better way to do this. I just want to split long string into 60 character lines but do not break words. So it doesn't have to add up to 60 characters just has to be less than 60.

下面的代码是我所拥有的,并且可以正常工作,但是我在想有一种更好的方法.有人吗?

The code below is what I have and it works but I'm thinking there's a better way. Anybody?

修改为使用StringBuilder,并修复了删除重复单词的问题.同样也不想使用正则表达式,因为我认为这会比现在的效率低.

Modified to use StringBuilder and fixed the problem of removing a repeating word. Also don't want to use regex because I think that would be less efficient than what I have now.

public static List<String> FormatMe(String Message)
{
    Int32 MAX_WIDTH = 60;
    List<String> Line = new List<String>();
    String[] Words;

    Message = Message.Trim();
    Words = Message.Split(" ".ToCharArray());

    StringBuilder s = new StringBuilder();
    foreach (String Word in Words)
    {
        s.Append(Word + " ");
        if (s.Length > MAX_WIDTH)
        {
            s.Replace(Word, "", 0, s.Length - Word.Length);
            Line.Add(s.ToString().Trim());
            s = new StringBuilder(Word + " ");
        }
    }

    if (s.Length > 0)
        Line.Add(s.ToString().Trim());

    return Line;
}

谢谢

推荐答案

尝试一下:

const Int32 MAX_WIDTH = 60;

string text = "...";
List<string> lines = new List<string>();
StringBuilder line = new StringBuilder();
foreach(Match word in Regex.Matches(text, @"\S+", RegexOptions.ECMAScript))
{
    if (word.Value.Length + line.Length + 1 > MAX_WIDTH)
    {
        lines.Add(line.ToString());
        line.Length = 0;
    }
    line.Append(String.Format("{0} ", word.Value));
}

if (line.Length > 0)
    line.Append(word.Value);

也请检查以下内容:如何做我使用正则表达式添加换行符吗?

这篇关于将长字符串分成60个字符的长行,但不要弄断单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆