大家好我需要一些帮助来创建一个以人类可读格式转换普通语法的函数:
语法如下所示:
[OPENTAG]
(type)name:value
[OPENTAG]
(type)name:value
(type)name:value
(type)name:value
[/CLOSETAG]
[/CLOSETAG]
想把它变成这个:
[OPENTAG] (type)name:value [OPENTAG] (type)name:value (type)name:value (type)name:value [/CLOSETAG] [/CLOSETAG]
private string textFormater(string input)
{
string[] lines = Regex.Split(input, "\r\n");
int tabs = 0;
string newtext = "";
foreach (string line in lines)
{
Match m = Regex.Match(line, "\\[.*\\]");
bool isTop;
bool isTopClose = false;
string tabtext = "";
if (m.Success)
{
if (line.Contains("/"))
{
tabs--;
isTopClose = true;
}
else
{
tabs++;
}
isTop = true;
}
else
{
isTop = false;
}
if (isTop && !isTopClose && tabs == 1)
{
newtext += line;
}
else if (isTop && !isTopClose)
{
for (int i = 1; i <= tabs - 1; i++)
{
tabtext += "\t";
}
newtext += "\r\n" + tabtext + line;
}
else
{
for (int i = 1; i <= tabs; i++)
{
tabtext += "\t";
}
newtext += "\r\n" + tabtext + line;
}
}
return newtext;
}
我有一个解决方案,但代码是如此凌乱和缓慢,在2mb文件中需要很长时间:) 谢谢你的帮助!
干杯
答案 0 :(得分:2)
尝试使用StringBuilder
作为输出文本而不仅仅是字符串,这样可以加快速度。
编辑:
这样做你想要的吗?
private static string textFormater2(string input)
{
string[] lines = Regex.Split(input, "\r\n");
int tabCount = 0;
StringBuilder output = new StringBuilder();
using (StringReader sr = new StringReader(input))
{
string l;
while (!string.IsNullOrEmpty(l = sr.ReadLine()))
{
if (l.Substring(0, 1) == "[")
if (l.Contains('/'))
tabCount--;
string tabs = string.Empty;
for (int i = 0; i < tabCount; i++)
tabs += "\t";
output.AppendLine(tabs + l);
if (l.Substring(0, 1) == "[")
if (!l.Contains('/'))
tabCount++;
}
}
return output.ToString();
}