LoginSignup
1
0

More than 1 year has passed since last update.

文字列の出現回数を数えたい

Last updated at Posted at 2021-08-01

特定の文字列の出現回数を数えたい場合、たとえばPythonだと

$ python3
Python 3.8.5 (default, Jul 28 2020, 12:59:40)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "AABABAAAB".count("AB")
3

というように、非常に簡単に書けるのですが、Javaでは一工夫が必要になります。

public static int count(String string, String target) {
    int i = -1;
    int c = 0;
    while ((i = string.indexOf(target, i+1))!=-1) c++;
    return c;
}

実際に使ってみると、次のようになります。

System.out.println(count("AABABAAAB", "A"));    //=> 6
System.out.println(count("AABABAAAB", "AB"));   //=> 3
System.out.println(count("AABABAAAB", "ABA"));  //=> 2
System.out.println(count("AABABAAAB", "AAAA")); //=> 0

想定通りに動いていそうですね(´・ω・`)

環境情報

D:\>javac --version
javac 11.0.10

D:\>java --version
openjdk 11.0.10 2021-01-19
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.10+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.10+9, mixed mode)

2021/08/01 22:45追記

上記のロジックは「文字列の出現回数を重複ありで数える」もので、Python3と同じように「文字列の出現回数を重複なしで数える」場合は以下のようにすべきでした。

public static int count(String string, String target) {
    int c = 0;
    int i = 0;
    int len = target.length();
    while ((i=string.indexOf(target, i))!=-1) {
        c++;
        i += len;
    }
    return c;
}
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0