如果字符串太长,我该如何用“ ...”来截断它们?

希望有人有好主意。我有这样的线:

abcdefg
abcde
abc

我需要的是,如果超过一定的长度,它们就会像这样显示出来:

abc ..
abc ..
abc

有没有简单的 C # 代码可以用来做这个?

68818 次浏览
public string TruncString(string myStr, int THRESHOLD)
{
if (myStr.Length > THRESHOLD)
return myStr.Substring(0, THRESHOLD) + "...";
return myStr;
}

Ignore the naming convention it's just in case he actually needs the THRESHOLD variable or if it's always the same size.

Alternatively

string res = (myStr.Length > THRESHOLD) ? myStr.Substring(0, THRESHOLD) + ".." : myStr;

Code behind:

string shorten(sting s)
{
//string s = abcdefg;
int tooLongInt = 3;


if (s.Length > tooLongInt)
return s.Substring(0, tooLongInt) + "..";


return s;
}

Markup:

<td><%= shorten(YOUR_STRING_HERE) %></td>

Maybe it is better to implement a method for that purpose:

string shorten(sting yourStr)
{
//Suppose you have a string yourStr, toView and a constant value


string toView;
const int maxView = 3;


if (yourStr.Length > maxView)
toView = yourStr.Substring(0, maxView) + " ..."; // all you have is to use Substring(int, int) .net method
else
toView = yourStr;
return toView;
}
string s = "abcdefg";
if (s.length > 3)
{
s = s.substring(0,3);
}

You can use the Substring function.

Sure, here is some sample code:

string str = "abcdefg";
if (str.Length > X){
str = str.Substring(0, X) + "...";
}

There isn't a built in method in the .NET Framework which does this, however this is a very easy method to write yourself. Here are the steps, try making it yourself and let us know what you come up with.

  1. Create a method, perhaps an extension method public static void TruncateWithEllipsis(this string value, int maxLength)

  2. Check to see if the passed in value is greater than the maxLength specified using the Length property. If the value not greater than maxLength, just return the value.

  3. If we didn't return the passed in value as is, then we know we need to truncate. So we need to get a smaller section of the string using the SubString method. That method will return a smaller section of a string based on a specified start and end value. The end position is what was passed in by the maxLength parameter, so use that.

  4. Return the sub section of the string plus the ellipsis.

A great exercise for later would be to update the method and have it break only after full words. You can also create an overload to specify how you would like to show a string has been truncated. For example, the method could return " (click for more)" instead of "..." if your application is set up to show more detail by clicking.

Here is the logic wrapped up in an extension method:

public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}

Usage:

var s = "abcdefg";


Console.WriteLine(s.Truncate(3));

Here's a version that accounts for the length of the ellipses:

    public static string Truncate(this string value, int maxChars)
{
const string ellipses = "...";
return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
}

I found this question after searching for "C# truncate ellipsis". Using various answers, I created my own solution with the following features:

  1. An extension method
  2. Add an ellipsis
  3. Make the ellipsis optional
  4. Validate that the string is not null or empty before attempting to truncate it.

    public static class StringExtensions
    {
    public static string Truncate(this string value,
    int maxLength,
    bool addEllipsis = false)
    {
    // Check for valid string before attempting to truncate
    if (string.IsNullOrEmpty(value)) return value;
    
    
    // Proceed with truncating
    var result = string.Empty;
    if (value.Length > maxLength)
    {
    result = value.Substring(0, maxLength);
    if (addEllipsis) result += "...";
    }
    else
    {
    result = value;
    }
    
    
    return result;
    }
    }
    

I hope this helps someone else.

I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.

But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.

I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...

        if (CurrentStatus.Length >= 3750)
{
// perform some truncation to free up some space.


// Lets get the status messages into an array for processing...
// We use the period as the delimiter, then skip the first item and re-insert into an array.


string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
.Skip(1).ToArray();


// Next we return the data to a string and replace any escaped returns with proper one.
CurrentStatus = (string.Join(".", statusArray))
.Replace("\\r\\n", Environment.NewLine);




}

Hope it helps someone out.

All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.

private string TruncateForDisplay(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
var returnValue = value;
if (value.Length > length)
{
var tmp = value.Substring(0, length) ;
if (tmp.LastIndexOf(' ') > 0)
returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
}
return returnValue;
}

Refactor with new C# features just for disclosure:

// public static class StringExtensions { ...


private static string? Truncate(this string? value, int maxChars)
=>
string.IsNullOrEmpty(value) ? value :
value.Length <= maxChars ? value :
value[..maxChars] + "...";

Checked as "Community wiki", be free to improve answer.