Có vẻ như đó chỉ là về tất cả mọi người trên thế giới có phiên bản riêng của phương pháp này vì vậy tôi nghĩ tôi sẽ chia sẻ phương pháp này là hay nhất.
Mã nguồn:
public static string Truncate(this string s, int length, bool atWord, bool addEllipsis)
{
// Return if the string is less than or equal to the truncation length
if (s == null || s.Length <= length)
return s;
// Do a simple tuncation at the desired length
string s2 = s.Substring(0, length);
// Truncate the string at the word
if (atWord)
{
// List of characters that denote the start or a new word (add to or remove more as necessary)
List<char> alternativeCutOffs = new List<char>() { ' ', ',', '.', '?', '/', ':', ';', '\'', '\"', '\'', '-' };
// Get the index of the last space in the truncated string
int lastSpace = s2.LastIndexOf(' ');
// If the last space index isn't -1 and also the next character in the original
// string isn't contained in the alternativeCutOffs List (which means the previous
// truncation actually truncated at the end of a word),then shorten string to the last space
if (lastSpace != -1 && (s.Length >= length + 1 && !alternativeCutOffs.Contains(s.ToCharArray()[length])))
s2 = s2.Remove(lastSpace);
}
// Add Ellipsis if desired
if (addEllipsis)
s2 += "...";
return s2;
}
Phương pháp này trả về một chuỗi cắt ngắn cắt ở "cuối của từ" gần nhất vị trí (các chuỗi trả lại sẽ luôn luôn nhỏ hơn hoặc bằng tham số chiều dài). The twist mà tôi đặt trên phiên bản của tôi mà bạn có thể chỉ định các dụng cụ cắt thay thế đúng hơn là chỉ spaces (khoảng trắng). Để minh họa cho lợi ích của việc này, hãy xem đoạn code dưới đây.
string s = "I like green, red, and yellow!";
string s2 = s.Truncate(12, true, false);
Yêu cầu: .Net Framework 3.5
Referrent: http://nickstips.wordpress.com/2010/02/12/c-truncate-a-string-at-the-end-of-a-word/