ホームページ >Java >&#&チュートリアル >Java 文字列内の部分文字列の出現を正しくカウントするにはどうすればよいですか?
文字列内の部分文字列の出現回数を確認する方法
多くの開発者は、部分文字列の出現頻度を判断しようとすると問題に遭遇します。指定された文字列内の出現。そのようなケースの 1 つは、次のアルゴリズムに関係します:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = str.indexOf(findStr, lastIndex); if (lastIndex != -1) count++; lastIndex += findStr.length(); } System.out.println(count);
なぜアルゴリズムは失敗するのですか?
インデックス 0 で最初に出現した "hello" を正常に識別したにもかかわらず、アルゴリズムは、後続の出現を検索するときに無限ループに入ります。これは、最初の出現箇所が見つかった後、lastIndex findStr.length() は 5 に等しくなりますが、indexOf() によって返される次の「-1」の結果により、lastIndex が 0 に設定されたまま while ループが再度反復されるためです。
問題を解決するにはどうすればよいですか?
この問題を解決するにはいくつかの方法があります。 1 つは、Apache Commons Lang の StringUtils.countMatches() など、別の部分文字列検索メソッドを利用する方法です。以下に例を示します:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; System.out.println(StringUtils.countMatches(str, findStr)); // Outputs 3
または、「-1」の場合を処理するように元のアルゴリズムを変更することもできます:
String str = "helloslkhellodjladfjhello"; String findStr = "hello"; int lastIndex = 0; int count = 0; while (lastIndex != -1) { lastIndex = str.indexOf(findStr, lastIndex); if (lastIndex != -1) { count++; lastIndex += findStr.length(); } else { break; // Exit the loop if no more occurrences are found } } System.out.println(count); // Outputs 3
以上がJava 文字列内の部分文字列の出現を正しくカウントするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。