1

私が文字列を持っているとしましょう:

あなたはきれいな<女性です>が、その<女の子はあなたよりも>きれいです。<>

英語で申し訳ありませんが、上記のテキストにある <> の数をどのように数えることができますか?

私はできることを知っています:

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

ただし、テキストが次のようなものであっても、それはカウントされます。

<<<<お元気ですか<<<<<_>>>

実際には <> のペアを数えたいだけなので、開始 < と終了 > が見つかったときにカウントが 1 ずつ進み、< が見つかったときにのみカウントを開始する必要があります。

4

3 に答える 3

4

このようにするのはどうですか。基本的に、以前に<に遭遇した場合にのみ、>をカウントする必要があります。または別の言い方をします。<を積み重ねて、>に遭遇したときにそれぞれ1つずつ使用します。

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.

編集

<<< >>>は1ではなく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.
于 2011-11-02T13:05:22.087 に答える
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 に答える
0

どうですか:

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