在截取字串時需要記錄每一個標籤是否關閉,如果截取到指定長度還有沒有關閉的標籤,那麼我們需要將標籤關閉,或者刪除掉未關閉的標籤。不考慮某些不需要關閉標籤的情況,html開始和結束標籤總是成對出現的,我們可以遍曆輸入的字串,並在標籤開始時放入堆棧中,遇到結束標籤時從堆棧中彈出一個元素,這樣遍曆到指定長度,堆棧中留下的標籤就是需要補全或者刪除掉的標籤。
下面是代碼實現,如果大家有更好的方法請給出來: 複製代碼 代碼如下:static char END_SLASH = '/';
/// <summary>
/// 安全的截斷字串
/// </summary>
/// <param name="input">輸入串</param>
/// <param name="length">截斷長度</param>
/// <param name="trimHalfTag">true:截斷半截標籤;false:補全半截標籤</param>
/// <param name="tagStartChar">標籤開始字元</param>
/// <param name="tagEndChar">標籤結束字元</param>
/// <param name="mustCloseTags">需要關閉的標籤數組</param>
/// <returns>length長度的字串</returns>
public static string SafeTrim(string input, int length, bool trimHalfTag, char tagStartChar, char tagEndChar, string[] mustCloseTags)
{
if (length <= 0) throw new ArgumentException("length 必須是正數");
if (mustCloseTags == null) throw new ArgumentNullException("mustCloseTags");
int inputLen = input.Length;
if (string.IsNullOrEmpty(input) || inputLen <= length) return input;
string result = string.Empty;
//聲明堆棧用來放標籤
Stack<string> tags = new Stack<string>();
for (int i = 0; i < length; i++)
{
char c = input[i];
if (c == tagStartChar)
{
string tag = string.Empty;
int tagIndex = i + 1;
bool isTagEnd = false;
bool isTagNameEnd = false;
result += c;
bool hasMarkTagInStack = false;
while (tagIndex < inputLen)
{
char tagC = input[tagIndex];
result += tagC;
tagIndex++;
if (tag == string.Empty && tagC == END_SLASH)
{
isTagEnd = true;
continue;
}
if (!isTagNameEnd)
{
if (char.IsLetter(tagC) || char.IsNumber(tagC))
{
tag += tagC;
}
else
{
isTagNameEnd = true;
}
}
if (!string.IsNullOrEmpty(tag))
{
if (isTagNameEnd && !hasMarkTagInStack)
{
if (isTagEnd)
{
tags.Pop();
}
else
{
tags.Push(tag);
}
hasMarkTagInStack = true;
}
}
if (isTagNameEnd)
{
if (tagC == tagEndChar)
{
i = tagIndex - 1;
break;
}
}
}
}
else
{
result += c;
}
}
while (tags.Count > 0)
{
string tag = tags.Pop();
bool isMustCloseTag = false;
foreach (string mustCloseTag in mustCloseTags)
{
if (string.Compare(mustCloseTag, tag, true) == 0)
{
isMustCloseTag = true;
break;
}
}
if (isMustCloseTag)
{
if (trimHalfTag)
{
int lastTagIndex = result.LastIndexOf(tagStartChar.ToString() + tag, StringComparison.CurrentCultureIgnoreCase);
result = result.Substring(0, lastTagIndex);
}
else
{
result += (tagStartChar.ToString() + END_SLASH + tag + tagEndChar);
}
}
}
return result;
}
轉載請保留連結 玉開的技術部落格