Skip to content

Instantly share code, notes, and snippets.

@sguzunov
Created May 29, 2016 21:01
Show Gist options
  • Save sguzunov/a65b179ce1ca77dc07074c4de92c1e93 to your computer and use it in GitHub Desktop.
Save sguzunov/a65b179ce1ca77dc07074c4de92c1e93 to your computer and use it in GitHub Desktop.
using System;
using System.Text;
class ReplaceTags
{
private const string Href = "href=\"";
private const string AnchorCloseTag = "</a>";
// <p>Please visit <a href="http://academy.telerik.com">our site</a> to choose a training course. Also visit <a href="www.devbg.org">our forum</a> to discuss the courses.</p>
// <p>Please visit [our site](http://academy.telerik.com) to choose a training course. Also visit [our forum](www.devbg.org) to discuss the courses.</p>
private static string ParseTags(string html)
{
int linkStartIndex = 0;
bool inAnchor = false;
bool inLink = false;
StringBuilder markDown = new StringBuilder();
StringBuilder link = new StringBuilder();
for (int i = 0; i < html.Length; i++)
{
if (inAnchor)
{
if (inLink)
{
if (html[i] != '"')
{
link.Append(html[i]);
}
else
{
link.Append(")");
inLink = false;
i = html.IndexOf('>', i);
markDown.Append('[');
}
}
// In content
else
{
if (html[i] == '<' && html[i + 1] == '/' && html[i + 2] == 'a')
{
markDown.Append(']' + link.ToString());
inAnchor = false;
i += AnchorCloseTag.Length - 1;
// Ready for a new link.
link.Clear();
}
else
{
markDown.Append(html[i]);
}
}
}
else if (html[i] == '<' && html[i + 1] == 'a')
{
inAnchor = true;
inLink = true;
linkStartIndex = html.IndexOf(Href, i) + Href.Length - 1;
i = linkStartIndex;
link.Append('(');
}
else
{
markDown.Append(html[i]);
}
}
return markDown.ToString();
}
static void Main()
{
string html = Console.ReadLine();
string markDown = ParseTags(html);
Console.WriteLine(markDown);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment