文字列中における特定文字の出現回数をカウントするには?[C#、VB].NET TIPS

» 2009年08月06日 05時00分 公開
[遠藤孝信デジタルアドバンテージ]

この記事は会員限定です。会員登録(無料)すると全てご覧いただけます。

「.NET TIPS」のインデックス

連載目次

 指定された文字列中に、特定の文字が何回出現するかをカウントしたい場合、標準ではそのようなメソッドは用意されていないが、次のようにして簡単に記述できる。

using System;

class Program {

  // 文字の出現回数をカウント
  public static int CountChar(string s, char c) {
    return s.Length - s.Replace(c.ToString(), "").Length;
  }

  static void Main() {

    string s = "この文字列の中の「の」の数は?";

    Console.WriteLine(CountChar(s, 'の')); // 出力:5
  }
}

Imports System

Class Program

  ' 文字の出現回数をカウント
  Public Shared Function CountChar(ByVal s As String, ByVal c As Char) As Integer
    Return s.Length - s.Replace(c.ToString(), "").Length
  End Function

  Shared Sub Main()

    Dim s As String = "この文字列の中の「の」の数は?"

    Console.WriteLine(CountChar(s, "の")) ' 出力:5
  End Sub
End Class

文字の出現回数をカウントするプログラム(上:C#、下:VB)

Copyright© Digital Advantage Corp. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。