Skip to main content
 首页 » 编程设计

c#之计算字符串中的开始和结束字符对

2024年02月23日29xiaohuochai

假设我有字符串:

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

抱歉是英文,但我怎么能数出上面的文本中有多少 <> 呢?

我知道我能做到:

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

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

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

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

请您参考如下方法:

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

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.