我想截断一个字符串,使其长度不超过给定值。我正在向数据库表写入数据,并希望确保写入的值满足列数据类型的约束。

例如,如果我能写以下内容,那就太好了:

string NormalizeLength(string value, int maxLength)
{
    return value.Substring(0, maxLength);
}

不幸的是,这会引发异常,因为maxLength通常超过字符串值的边界。当然,我可以写一个像下面这样的函数,但我希望这样的东西已经存在了。

string NormalizeLength(string value, int maxLength)
{
    return value.Length <= maxLength ? value : value.Substring(0, maxLength);
} 

执行此任务的难以捉摸的API在哪里?有吗?


当前回答

这是一个vb.net解决方案,标记if(虽然丑陋)语句提高性能,因为当字符串已经小于maxlength时,我们不需要substring语句… 通过使它成为字符串的扩展,它很容易使用…

 <System.Runtime.CompilerServices.Extension()> _
    Public Function Truncate(String__1 As String, maxlength As Integer) As String
        If Not String.IsNullOrEmpty(String__1) AndAlso String__1.Length > maxlength Then
            Return String__1.Substring(0, maxlength)
        Else
            Return String__1
        End If
    End Function

其他回答

2016年c#字符串仍然没有截断方法。 但是-使用c# 6.0语法:

public static class StringExtension
{
  public static string Truncate(this string s, int max) 
  { 
    return s?.Length > max ? s.Substring(0, max) : s ?? throw new ArgumentNullException(s); 
  }
}

它就像一个魔法:

"Truncate me".Truncate(8);
Result: "Truncate"

.NET框架有一个API可以像这样截断字符串:

Microsoft.VisualBasic.Strings.Left(string, int);

但在c#应用程序中,你可能更喜欢编写自己的程序,而不是依赖于Microsoft.VisualBasic.dll,后者存在的主要原因是向后兼容。

截断字符串

public static string TruncateText(string strText, int intLength)
{
    if (!(string.IsNullOrEmpty(strText)))
    {                                
        // split the text.
        var words = strText.Split(' ');

        // calculate the number of words
        // based on the provided characters length 
        // use an average of 7.6 chars per word.
        int wordLength = Convert.ToInt32(Math.Ceiling(intLength / 7.6));

        // if the text is shorter than the length,
        // display the text without changing it.
        if (words.Length <= wordLength)
            return strText.Trim();                

        // put together a shorter text
        // based on the number of words
        return string.Join(" ", words.Take(wordLength)) + " ...".Trim();
    }
        else
        {
            return "";
        }            
    }

为什么不:

string NormalizeLength(string value, int maxLength)
{
    //check String.IsNullOrEmpty(value) and act on it. 
    return value.PadRight(maxLength).Substring(0, maxLength);
}

即在事件值中。Length < maxLength填充空格到末尾或截断多余部分。

最近c#中最简单的方法是:

string Trunc(string s, int len) => s?.Length > len ? s.Substring(0, len) : s;

它返回截断值较长的字符串和原始字符串为其他情况-包括空输入-这是由?一元运算符。