像这样做怎么办。基本上,如果您之前遇到过 < ,您应该只计算 > 。或者换一种说法。您将 < 堆叠起来,然后在遇到 > 时使用其中的一个。
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.
编辑
我认为 <<<>>> 应该算 3 而不是 1,所以你需要在上面快速修复。要将 <<<>>> 仅计为 1,请更改为
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.