Count pair of start and closing character within a string?

207 Views Asked by At

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.

3

There are 3 best solutions below

7
On BEST ANSWER

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.
0
On

How about:

int count = b.Split('<').Count(t => t.Contains('>'));
0
On

try this out.

        string test = "You are pretty <<<lady>>> but that <girl> is prettier <than> you.";

        int found = 0;
        int count = 0;
        for (int i = 0; i < test.Length; i++) {

            if (test[i] == '<')
            {
                found++;
            }
            else if (test[i] == '>'&&found!=1)
            {
                found--;
            }
            else if (test[i] == '>'&&found==1) {
                count++;
                found = 0;

            }else continue;

        }
        return count;