1

假设我有字符串:

你是漂亮的<女士>,但那个<女孩比你>漂亮。<>

对不起英语,但我怎么能数出上面的文字中有多少 <> ?

我知道我可以这样做:

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

但即使文本是这样的,那也算数:

<<<<,你<<<<<好吗>>>

实际上,我只想计算成对的 <> ,因此当它找到开始 < 和结束 > 时计数会加一,并且应该仅在找到 < 时才开始计数。

4

3 回答 3

4

像这样做怎么办。基本上,如果您之前遇到过 < ,您应该只计算 > 。或者换一种说法。您将 < 堆叠起来,然后在遇到 > 时使用其中的一个。

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.
于 2011-11-02T13:05:22.087 回答
0

怎么样:

int count = b.Split('<').Count(t => t.Contains('>'));
于 2011-11-02T13:31:53.483 回答
0

试试这个。

        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;
于 2011-11-02T13:38:45.730 回答