我有一个从数据库中取出的大文本字段
rs.Item("content")
如何将此限制为100个字符,但不能删除最后一个字。例如“将此限制为100 cha ...”
我想将...添加到最后。
由于
答案 0 :(得分:1)
Console.WriteLine(content.Substring(content.IndexOf(" ", 99)) + "...");
答案 1 :(得分:1)
我使用以下方法:
''' <summary>
''' Creates a shortend version of a string, with optional follow-on characters.
''' </summary>
''' <param name="stringToShorten">The string you wish to shorten.</param>
''' <param name="newLength">
''' The new length you want the string to be (nearest whole word).
''' </param>
''' <param name="isAbsoluteLength">
''' If set to <c>true</c> the string will be no longer than <i>newLength</i>.
''' and will cut off mid-word.
''' </param>
''' <param name="stringToAppend">
''' What you'd like on the end of the shorter string to indicate truncation.
''' </param>
''' <returns>The shorter string.</returns>
Public Shared Function ShortenString(stringToShorten As String, newLength As Integer, isAbsoluteLength As Boolean, stringToAppend As String) As String
If Not isAbsoluteLength AndAlso (newLength + stringToAppend.Length > stringToShorten.Length) Then
' requested length plus append will be longer than original
Return stringToShorten
ElseIf isAbsoluteLength AndAlso (newLength - stringToAppend.Length > stringToShorten.Length) Then
' requested length minus append will be longer than original
Return stringToShorten
Else
Dim cutOffPoint As Integer
If Not isAbsoluteLength Then
' Find the next space after the newLength.
cutOffPoint = stringToShorten.IndexOf(" ", newLength)
Else
' Just cut the string off at exactly the length required.
cutOffPoint = newLength - stringToAppend.Length
End If
If cutOffPoint <= 0 Then
cutOffPoint = stringToShorten.Length
End If
Return stringToShorten.Substring(0, cutOffPoint) + stringToAppend
End If
End Function
答案 2 :(得分:0)
Dim newString = New String(
yourString
.ToCharArray()
.Take(100)
.TakeWhile(Function(c) c <> " "c).ToArray())
善,
丹
答案 3 :(得分:0)
这是我的C#扩展方法
/// <summary>
/// Creates a shortend version of a string, with optional follow-on characters.
/// </summary>
/// <param name="stringToShorten">The string you wish to shorten.</param>
/// <param name="newLength">
/// The new length you want the string to be (nearest whole word).
/// </param>
public static string ShortenString(this string stringToShorten, int newLength)
{
if (newLength > stringToShorten.Length) return stringToShorten;
int cutOffPoint = stringToShorten.IndexOf(" ", newLength -1);
if (cutOffPoint <= 0)
cutOffPoint = stringToShorten.Length;
return stringToShorten.Substring(0, cutOffPoint);
}
答案 4 :(得分:0)
好像你可以用这样的东西击中它,这不会把最后一个字分成碎片。其他的解决方案似乎导致了“像......这样的句子”,这些句子没有突破字界,但我可能已经错过了,因为我没有仔细检查。
if (text.Length < 100)
return text;
var words = text.Split(' ');
var sb = new StringBuilder(128);
foreach (string w in words)
{
if (sb.Length + w.Length > 100)
{
sb.Append("...");
return sb.ToString();
}
sb.Append(w).Append(" ");
}
return sb.ToString();