gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:32:44 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com