c# - 将长字符串分成 60 个字符的长行但不要打断单词

标签 c# .net string

必须有更好的方法来做到这一点。 我只想将长字符串拆分为 60 个字符的行,但不要打断单词。所以它不必加起来最多 60 个字符只需少于 60 个即可。

下面的代码是我所拥有的并且可以正常工作,但我认为还有更好的方法。有人吗?

修改为使用StringBuilder,修复了去除重复词的问题。 也不想使用正则表达式,因为我认为那会比我现在使用的效率低。

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

谢谢

最佳答案

另一个(现已测试)示例,与 Keith approach 非常相似:

static void Main(string[] args)
{
    const Int32 MAX_WIDTH = 60;

    int offset = 0;
    string text = Regex.Replace(File.ReadAllText("oneline.txt"), @"\s{2,}", " ");
    List<string> lines = new List<string>();
    while (offset < text.Length)
    {
        int index = text.LastIndexOf(" ", 
                         Math.Min(text.Length, offset + MAX_WIDTH));
        string line = text.Substring(offset,
            (index - offset <= 0 ? text.Length : index) - offset );
        offset += line.Length + 1;
        lines.Add(line);
    }
}

我在 this file 上运行了它所有换行符手动替换为“”。

关于c# - 将长字符串分成 60 个字符的长行但不要打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678051/

相关文章:

c# - 查找目录中不存在的文件名

c# - 类实例创建限制

c# - 如何上传附件到服务器,Net Core+React(Redux)

c# - 需要将通用方法移动到另一个类并从 C# 中的不同类调用它

.net - 创建自定义SAML token

c++ - 需要格式化字符串中的字符优先级

c# - 在 Qt 项目中使用 PICkitS.dll

c# - 如何使用变量作为类型

php - 如果一个为空,如何将变量分配给两个字符串之一?

python - 我如何获得由 Pandas 数据框中的值表示的两个连接代码的聚合百分比