[英]Count pair of start and closing character within a string?
假設我有字符串:
你很
<
小姐>
但<
女孩>
是漂亮<
超過>
你。
對不起英文,但我怎么能算出上面文字中有多少<>?
我知道我能做到:
int count = message.Length - message.Replace("<", "").Replace(">", "").Length;
但即使文本是這樣的,這也算得上:
嘿
<<<<
你<<<<<
你怎么做>>>
實際上我只想計算<>的對數,所以當它找到一個起始<和結束>時,計數會加1,並且只有在找到<時才開始計數。
怎么樣這樣做。 基本上你應該只計算>如果你在之前的某個時間遇到過<。 或以另一種方式說。 你堆疊了<s,然后當你遇到一個>時,你會使用其中一個。
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,所以你需要快速解決上面的問題。 因為它只計數<<< >>>,改為此
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.
怎么樣:
int count = b.Split('<').Count(t => t.Contains('>'));
試試這個。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.