Search code examples
c#winformscolorsspinningspintax

C# Spintax Coloring


Spintax is used for getting multiple pieces of content from one piece ex: Spintax: The {dog|cat} {ran|jumped} very {quietly|far {ahead|away}}. That would return sentences like these:
The dog ran very quietly.
The cat jumped very quietly.
The dog jumped very far ahead.
The cat ran very far away.

I figured out how to turn the spintax into random different sentences but I now want to display the spintax with coloring (in a rich text box). What I mean by that is everything between the {} and the {} themselves would be a different color(blue). When there are {} inside other {} it would be another color(green). When generating sentences I started from the deepest brackets (the {} that did not have any other {} inside them). I think that for the coloring I have to start from the outside but I don't know how. Can anyone help me?


Solution

  • You can do something like:

    var input = "hello {one {two}} there";
    var depth = 0;
    for (int index = 0; index < input.Length; index++)
    {
        if (input[index]==('{'))
            depth++;
        else if (input[index]==('}'))
            depth--;
    
        // depending on your depth, use whatever color you want
        // maybe have an array of colors "color_array", and just
        // use color_array[depth] to get your color
    }
    

    You'll have to have a look at your end cases and how you deal with the { and } colorwise, but you should be able to go on from here.