在截取字符串時需要記錄每一個標簽是否關閉,如果截取到指定長度還有沒有關閉的標簽,那麼我們需要將標簽關閉,或者刪除掉未關閉的標簽。不考慮某些不需要關閉標簽的情況,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;
}
轉載請保留鏈接
玉開的技術博客