Get correct string position C#

I have a string:

string str = "Wishing you {all a great} day {ahead}. \n Thanks a lot \n } \n for {your} help!}"

I read the string line by line. So at present I have 4 lines with me:

1. Wishing you {all a great} day {ahead}.
2. Thanks a lot
3.  }
4. for {your} help!}

The intention is to check whether "}" is the closing brace of the string and that it should not appear as a single character in any of the other lines.

My approach is this:

In the above string, I want to get the position of the "}" in the main string. And then check whether there are characters after that position to check whether its the closing brace.

But Iam unable to get the correct position of "}" as it may appear in other lines as well.

Is there any better way to go about this?

Jon Skeet
people
quotationmark

Within a single string, it sounds like you should iterate over the characters in the string and keep a count of how many opening and how many closing braces you've seen. Something like this:

int open = 0;
for (int i = 0; i < text.Length; i++)
{
    switch (text[i])
    {
        case '{':
            open++;
            break;
        case '}':
            if (open > 0)
            {
                open--; // Matches an opening brace
            }
            else
            {
                // Whatever you want to do for an unmatched brace
            }
            break;
        default: // Do nothing
            break;
    }
}

If you need to know where the opening brace was, you might want a Stack<int> instead of just a count. Then when you see a { you push the index (i) onto the stack. When you see a }, if the stack isn't empty you pop it to find the matching opening brace.

Next you need to consider whether you ever need to escape the braces to remove their "special" meaning... at which point things become more complicated again.

people

See more on this question at Stackoverflow