(:3[kanのメモ帳]

個人ゲーム開発者kan.kikuchiのメモ的技術ブログ。月木更新でUnity関連がメイン。

(:3[kanのメモ帳]


本ブログの運営者kan.kikuchiが個人で開発したゲームです!

    

文字列の中に、任意の文字列がいくつあるか【C#】【拡張メソッド】


このエントリーをはてなブックマークに追加



はじめに

タイトル通り、今回は文字列の中に、任意の文字列がいくつあるかを調べる方法の記事です。

イメージとしては以下のような感じ。

string str = "ああいううえええええおお";

Debug.Log (CountOf (str, "あ"));    //"ああいううえええええおお" の中に"あ"が何個あるか
Debug.Log (CountOf (str, "ええ"));
Debug.Log (CountOf (str, "えお"));
Debug.Log (CountOf (str, "a"));

2
2
1
0



IndexOf

stringに任意の文字列がいくつあるかを数えるメソッドはありませんが、

似たようなものに、indexofというものがあります。

文字列内に指定した文字列と一致する部分があるかを探し、見つかったら、最初に見つかった位置を0以上の整数で返します。見つからなければ、-1を返します。

文字列内に指定された文字列があるか調べ、その位置を知る: .NET Tips: C#, VB.NET


さらに、indexofは第二引数に検索を開始するインデックスを指定できます。

具体的には以下のような感じです。

string str = "あいうえおあいうえお";

//indexが4、つまり最初の"お"から"うえ"を探す
Debug.Log (str.IndexOf("うえ", 4));

7



CountOf

indexofを利用して文字列の中に、任意の文字列がいくつあるかを数える

CountOfを作ってみました。

/// <summary>
/// 指定した文字列がいくつあるか
/// </summary>
public static int CountOf(string target, params string[] strArray){
  int count = 0;

  foreach (string str in strArray) {
    int index = target.IndexOf (str, 0);
    while (index != -1) {
      count++;
      index = target.IndexOf (str, index + str.Length);
    }
  }

  return count;
}  


引数が可変長なので複数の文字列を同時に数えることも可能です。

string str = "ああいううえええええおお";
Debug.Log (CountOf (str, "あ", "い")); //"ああいううえええええおお" の中に"あ"と"い"が何個あるか

3



拡張メソッド

毎度CountOfをつくるのは面倒なので、stringの拡張メソッドとして作ってみました。

using System;
using System.Collections.Generic;

/// <summary>
/// string 型の拡張メソッドを管理するクラス
/// </summary>
public static partial class StringExtensions{

  /// <summary>
  /// 指定した文字列がいくつあるか
  /// </summary>
  public static int CountOf(this string self, params string[] strArray){
    int count = 0;

    foreach (string str in strArray) {
      int index = self.IndexOf (str, 0);
      while (index != -1) {
        count++;
        index = self.IndexOf (str, index + str.Length);
      }
    }

    return count;
  }

}  


これを使うと以下のような感じに。

string str = "ああいううえええええおお";
Debug.Log (str.CountOf("あいう", "えお")); //"ああいううえええええおお" の中に"あいう", "えお"が何個あるか

2


簡単、便利!