using System;
using System.Text;
namespace XmlFormater
{
class Program
{
static void Main(string[] args)
{
string intput = "<a>123<b>456<c/></b></a>";
Console.WriteLine(Fmt(intput));
Console.ReadKey();
}
static string Fmt(string raw)
{
StringBuilder fmt = new StringBuilder();
int indent = 0;
int offset = 0;
while (offset != raw.Length)
{
// get special tag index
var start = raw.IndexOf('<', offset);
var mid = raw.IndexOf('/', offset);
var end = raw.IndexOf('>', offset);
// tag like </.. means end, decrease indent
if (start + 1 == mid)
{
indent -= 1;
}
// tag like ...< means content before start tag, append the content
if (offset < start)
{
fmt.Append(' ', indent * 4);
fmt.Append($"{raw.Substring(offset, start - offset)}\r\n");
}
// append tag with indent
fmt.Append(' ', indent * 4);
fmt.Append($"{raw.Substring(start, end - start + 1)}\r\n");
// tag start, increase indent
if (mid > end)
{
indent += 1;
}
//do offset
offset = end + 1;
}
return fmt.ToString();
}
}
}
Question_ID: Q001
Language: csharp
Time Cost: 0 min
Time Complexity: O(n)
Solution
My Code
Other
There is no exception check.