c# - 在 C# 中的标签中显示全文

标签 c# .net string winforms substring

我在 windows 窗体 中有一个 label 控件。我想在 label 中显示全文。条件是这样的:

  • 如果文本长度超过 32 个字符,它将出现在新行中。
  • 如果可能,按完整单词拆分,不带连字符 (-)。

    到目前为止,我已经达到了以下代码:

       private void Form1_Load(object sender, EventArgs e)
        {
            string strtext = "This is a very long text. this will come in one line.This is a very long text. this will come in one line.";
            if (strtext.Length > 32)
            {              
                IEnumerable<string> strEnum = Split(strtext, 32);
                label1.Text =string.Join("-\n", strEnum);
            }         
        }
        static IEnumerable<string> Split(string str, int chunkSize)
        {
            return Enumerable.Range(0, str.Length / chunkSize)
                .Select(i => str.Substring(i * chunkSize, chunkSize));
        }
    

但问题是最后一行没有完全显示,因为它按 32 个字符拆分。

还有其他方法可以实现吗?

最佳答案

我不知道你是否会接受不使用 linq 的答案,但这很简单:

string SplitOnWholeWord(string toSplit, int maxLineLength)
{
    StringBuilder sb = new StringBuilder();
    string[] parts = toSplit.Split();
    string line = string.Empty;
    foreach(string s in parts)
    {
        if(s.Length > 32)
        {
            string p = s;
            while(p.Length > 32)
            {
                int addedChars = 32 - line.Length;
                line = string.Join(" ", line, p.Substring(0, addedChars));
                sb.AppendLine(line);
                p = p.Substring(addedChars);
                line = string.Empty;
            }
            line = p;
        }
        else
        {
            if(line.Length + s.Length > maxLineLength)
            {
                sb.AppendLine(line);
                line = string.Empty;
            }
            line = (line.Length > 0 ? string.Join(" ", line, s) : s);
        }
    }
    sb.Append(line.Trim());
    return sb.ToString();
}

调用

string result = SplitOnWholeWord(strtext, 32);

可以很容易地在扩展方法中转换它:

将上面的代码放在一个单独的文件中,并创建一个静态类

public static class StringExtensions
{
     public static string SplitOnWholeWord(this string toSplit, int maxLineLength)
     {
          // same code as above.....
     }

}

并这样调用它:

string result = strtext.SplitOnWholeWord(32);

关于c# - 在 C# 中的标签中显示全文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436176/

相关文章:

c# - 我们如何使用 Crystal Reports 将公式中的数字转换为单词?

c# - VirtualKey C# Windows 应用商店应用程序

c# - Asp.net Mvc、Razor 和本地化

.net - 无法在 Windows XP 下运行 Light Switch 2012 程序

.net - Entity Framework 不在数据库中保存数据条目

c - C 中的格式检查

c# - 返回结果为 "::1"的 Request.UserHostAddress 问题

.net - 连接已成功建立...(提供程序 : SSL Provider, 错误:31 - 加密(ssl/tls)握手失败)

c++ - push_back()文件系统::path的.string()。data()的怪异行为导致生成 “vector<const char *>”

javascript - 如何在javascript中突出显示重叠的字符串?