应该很容易通过使用来确定级别string.IndexOf
:
string line = file.ReadLine();
int level = line.IndexOf('-');
level = (level - 1)/2;
处理关卡的逻辑更有趣一些。像下面这样的东西应该很好用。
int lastLevel = -1;
string line;
while ((line = file.ReadLine()) != null)
{
int level = GetLevel(line); // from code above
int diff = level - lastLevel;
if (diff > 1)
{
// skipping multiple levels forward is probably an error.
throw new ApplicationException();
}
if (diff == 1)
{
// next level. Add a <ul>
WriteUl();
}
else if (diff == 0)
{
// same level. Add an <li>
WriteLi(line);
}
else
{
// need to add </ul>, possibly multiple times
do
{
WriteUlEnd();
--lastLevel;
} while (lastLevel > level);
}
lastLevel = level;
}
如果你只有你展示的数据,那真的是唯一的方法。你必须计算空间。