gpt4 book ai didi

c# - 在 .NET/C# 中从数据库检索的子字符串值

转载 作者:太空狗 更新时间:2023-10-30 01:59:50 25 4
gpt4 key购买 nike

我正在使用以下内容从我的数据库中读取值:

    while (reader.Read())
{
newsLabel.Text += "<div style='float:left;'>" + reader["body"] + "</div>";
}

我在想。如何将“正文”的值减少到仅 0.20 个字符?

有我可以使用的 Substring 函数吗?

非常感谢

最佳答案

假设 body 列包含一个字符串,您可以像这样截断它:

var body = (String) reader["body"];
var truncatedBody = body.Substring(0, Math.Min(body.Length, 20));

如果该列可以为 null,您必须在调用 Substring 之前检查它。

Substring 如果请求的子字符串长度比实际字符串的长度长,将抛出异常。这就是为什么您必须使用字符串长度和所需子字符串长度中的最小值。

如果你经常这样做,你可以创建一个扩展方法:

public static class StringExtensions {

public static String Truncate(this String str, Int32 length) {
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (str == null)
return String.Empty;
return str.Substring(0, Math.Min(str.Length, length));
}

}

你可以这样使用它:

((String) reader["body"]).Truncate(20)

关于c# - 在 .NET/C# 中从数据库检索的子字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015131/

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