-8

I'm doing a codewars kate where I need to implement code highlighting. I need to split the string of code into strings of repeated characters, add proper highlighting tags to them and finally connect it all and return. You can train this kata on your own (https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting). The first step I thought of is to split the code by repeated characters. But i found it hard to come up with working algorithm. So, I need your help.

Input: "FFFR345F2LL"

Output: "FFF", "R", "345", "F", "2", "LL"

  • "345" is not a set of repeated characters. – JDB May 03 '19 at 14:55
  • you can use Regex to accomplish it. https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times is an example of matching 10 times, not 3, but you get the idea – Marshall Tigerus May 03 '19 at 14:55
  • 3
    This isn't a coding service I'm afraid. You need to show what you have tried. – DavidG May 03 '19 at 14:57
  • You don't need to split the string, you can just walk the string and examine each character – Rufus L May 03 '19 at 15:06

1 Answers1

0

Instead of splitting the string and then putting it back together again, you can just walk the string one character at a time, and build a result string from it. If you compare the current character with the previous character, you can determine whether or not to add a closing tag first, or just append the current character with the previous one (i.e. group "repeated" characters).

private static string GetOpeningSpan(char chr)
{
    // return an opening span with the correct color
    var validCharacters = new[] 
        {'F', 'L', 'R', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    if (!validCharacters.Contains(chr)) return "<span>";

    var color = chr == 'F' ? "pink" : chr == 'L' ? "red" : chr == 'R' ? "green" : "orange";

    return $"<span style=\"color: {color}\">";
}

private const string ClosingSpan = "</span>";

private static string GetHighlightedString(string input)
{
    if (string.IsNullOrWhiteSpace(input)) return input;

    // Add the opening span and first character
    var result = new StringBuilder().Append(GetOpeningSpan(input[0]) + input[0]);

    for (int i = 1; i < input.Length; i++)
    {
        var thisChar = input[i];
        var prevChar = input[i - 1];

        // If this character is the same as the previous one, just add it
        if (thisChar == prevChar || (char.IsDigit(thisChar) && char.IsDigit(prevChar)))
        {
            result.Append(thisChar);
        }
        else
        {
            // Add a closing span, and opnening span, and this character
            result.Append(ClosingSpan + GetOpeningSpan(thisChar) + thisChar);
        }
    }

    // Add a final closing span
    result.Append(ClosingSpan);

    return result.ToString();
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43