using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringTruncateDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("字符串截断测试...");
var input = "ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services.";
var output = TruncateString(input, 12, TruncateOptions.FinishWord | TruncateOptions.IncludeEllipsis | TruncateOptions.AllowLastWordToGoOverMaxLength);
Console.WriteLine("截断后的字符串为:{0}", output);
Console.WriteLine("字符串截断测试已结束,请按任意键退出...");
Console.ReadKey();
}
#region 截断字符串,提供枚举选项,可保留完整单词
/// <summary>
/// 截断字符串,提供枚举选项,可保留完整单词
/// </summary>
/// <param name="valueToTruncate">需处理的字符串</param>
/// <param name="maxLength">字符数</param>
/// <param name="options">截断选项</param>
/// <returns></returns>
public static string TruncateString(string valueToTruncate, int maxLength, TruncateOptions options)
{
if (valueToTruncate == null)
{
return "";
}
if (valueToTruncate.Length <= maxLength)
{
return valueToTruncate;
}
var includeEllipsis = (options & TruncateOptions.IncludeEllipsis) ==
TruncateOptions.IncludeEllipsis;
var finishWord = (options & TruncateOptions.FinishWord) ==
TruncateOptions.FinishWord;
var allowLastWordOverflow =
(options & TruncateOptions.AllowLastWordToGoOverMaxLength) ==
TruncateOptions.AllowLastWordToGoOverMaxLength;
var retValue = valueToTruncate;
if (includeEllipsis)
{
maxLength -= 1;
}
int lastSpaceIndex = retValue.LastIndexOf(" ",
maxLength, StringComparison.CurrentCultureIgnoreCase);
if (!finishWord)
{
retValue = retValue.Remove(maxLength);
}
else if (allowLastWordOverflow)
{
int spaceIndex = retValue.IndexOf(" ",
maxLength, StringComparison.CurrentCultureIgnoreCase);
if (spaceIndex != -1)
{
retValue = retValue.Remove(spaceIndex);
}
}
else if (lastSpaceIndex > -1)
{
retValue = retValue.Remove(lastSpaceIndex);
}
if (includeEllipsis && retValue.Length < valueToTruncate.Length)
{
retValue += "...";
}
return retValue;
}
#endregion
#region
/// <summary>
/// 截断字符串用的枚举
/// </summary>
[Flags]
public enum TruncateOptions
{
/// <summary>
/// 不作任何处理
/// </summary>
None = 0x0,
/// <summary>
/// 保留完整单词
/// </summary>
FinishWord = 0x1,
/// <summary>
/// 允许最后一个单词超过最大长度限制
/// </summary>
AllowLastWordToGoOverMaxLength = 0x2,
/// <summary>
/// 字符串最后跟省略号
/// </summary>
IncludeEllipsis = 0x4
}
#endregion
}
}