问题描述
我正在尝试用 c# 编写一个标记编辑器,其中一部分是检测哪些标签正在影响插入符当前所在的位置。 示例:
<b>Tes|ting</b><u><i>Testing</i>Testing</u> (caret '|' at index 6)
Answer: [b]
<b>Testing<u><i>Test|ing</i>Tes</b>ting</u> (caret '|' at index 20)
Answer: [b,u,i]
这是我目前拥有的代码,在“GetTags()”中,我将字符串拆分为 2 个队列,分别代表插入符所在位置的前后标签。我尝试了从两个队列中弹出元素的方法来尝试解决问题,但我一直得到错误的结果。我认为我在创建 2 个数据结构的正确轨道上,但我不知道 Queue 是否是我需要的。
public class Tag
{
public enum TagType
{
bold,italic,underline,}
public TagType type;
public bool opening;
public Tag(TagType type,bool opening)
{
this.type = type;
this.opening = opening;
}
public static Tag GetTagFromString(string str)
{
switch (str)
{
case "<b>": return new Tag(TagType.bold,true);
case "</b>": return new Tag(TagType.bold,false);
case "<i>": return new Tag(TagType.italic,true);
case "</i>": return new Tag(TagType.italic,false);
case "<u>": return new Tag(TagType.underline,true);
case "</u>": return new Tag(TagType.underline,false);
}
return null;
}
public static List<TagType> GetTags(string str,int index)
{
Queue<Tag> backQueue = new Queue<Tag>();
Queue<Tag> forwardQueue = new Queue<Tag>();
// populate the back queue
int i = index;
while (true)
{
int lastopening = str.LastIndexOf('<',i);
int lastClosing = str.LastIndexOf('>',i);
if (lastopening != -1 && lastClosing != -1)
{
string tagStr = str.Substring(lastopening,lastClosing - lastopening + 1);
Tag tag = GetTagFromString(tagStr);
backQueue.Enqueue(tag);
i = lastopening - 1;
if (i < 0)
break;
}
else
break;
}
// populate the front stack
i = index;
while (true)
{
int nextopening = str.IndexOf('<',i);
int nextClosing = str.IndexOf('>',i);
if (nextopening != -1 && nextClosing != -1)
{
string tagStr = str.Substring(nextopening,nextClosing - nextopening + 1);
Tag tag = GetTagFromString(tagStr);
forwardQueue.Enqueue(tag);
i = nextClosing + 1;
}
else
break;
}
List<TagType> tags = new List<TagType>();
// populate 'tags' list with the tags affecting the index here
return tags;
}
public override string ToString()
{
string str = "<";
if (!opening)
str += "/";
switch (type)
{
case TagType.bold:
str += "b";
break;
case TagType.italic:
str += "i";
break;
case TagType.underline:
str += "u";
break;
}
str += ">";
return str;
}
}
希望就我如何解决这个问题提供任何意见,并且非常感谢任何人对我提供的代码有任何问题。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)