Search code examples
c#.net.net-4.0string-search

Count pair of start and closing character within a string?


Let's say I have the string:

You are pretty <lady> but that <girl> is prettier <than> you.

Sorry about the English but how could I count how many <> there are in the above text ?

I know I could do:

int count = message.Length - message.Replace("<", "").Replace(">", "").Length;

But that would count even if the text was like this:

Hey <<<< you <<<<< how you doing >>>

When in fact I just want to count the pairs of <> so the count goes by one when it finds a starting < and ending > and should only starting counting when < is found.


Solution

  • What about doing it like this. Basically you should only count the > if you have encountered a < at some time before. Or said in another way. You stack up <'s, and then you use one of them each when you encounter a >.

    string test = "You are pretty <lady> but that <girl> is prettier <than> you.";
    
    int startcount = 0;
    int paircount = 0;
    foreach( char c in test ){
      if( c == '<' )
        startcount++;
      if( c == '>' && startcount > 0 ){
        startcount--;
        paircount++;
      }
    }
    //paircount should now be the value you are after.
    

    EDIT

    I thought that <<<>>> should count 3 not 1, so then you need a quick fix above. For it to count <<<>>> as only 1, change to this

    string test = "You are pretty <lady> but that <girl> is prettier <than> you.";
    
    bool foundstart = false;
    int paircount = 0;
    foreach( char c in test ){
      if( c == '<' )
        foundstart = true;
      if( c == '>' && foundstart ){
        foundstart = false;
        paircount++;
      }
    }
    //paircount should now be the value you are after.