この記事では、別の文字列に文字列の発生数を記載するJavaの方法について説明します。次のように、参照のために共有してください。
Javaは、文字列が別の文字列に表示される回数をカウントします
コードは次のとおりです。
packed me.chunsheng.javatest; Import java.util.regex.matcher; import java.util.regex.pattern;/*** 16/10/11にwei_springによって作成されました。 * <p>*統計文字列が別の文字列に表示される回数*定期的な一致の方法。文字列が特別な文字列ではないと仮定します*例:Finder( "Adadadadauada"、 "ada")は不正確です。 *別のトラバーサルは上記の状況を解決します。 * 2つの間の時間は次のとおりです(ナノ秒単位):レギュラーは明らかに時間がかかり、レギュラーは統計には使用されていません!!! * Finder:3 * Findertime:1579549 * getCount:4 * getCounttime:34506 */public class substringcount {public static void main(string [] args){system.out.println( "wulin.comテスト結果:"); long current1 = system.nanotime(); System.out.println( "Finder:" + Finder( "Adadadadauada"、 "Ada")); system.out.println( "indertime:" +(system.nanotime() - current1)); long current2 = system.nanotime(); system.out.println( "getCount:" + getCount( "adadadadauauda"、 "ada")); system.out.println( "getCountTime:" +(system.nanotime() - current2)); } public static int getCount(string source、string sub){int count = 0; int length = source.length() - sub.length(); for(int i = 0; i <length; i ++){string sourcebak = source.substring(i、i+sub.length()); int index = sourcebak.indexof(sub); if(index!= -1){count ++; }} return count; } public static int Finder(String Source、String Regexstr){String Regex = "[a-za-z]+"; if(regexstr!= null &&!regexstr.equals( "")){regex = regexstr; }パターン式= pattern.compile(regex); matcher matcher = expression.matcher(source); int n = 0; while(matcher.find()){n ++; } return n; }}実行結果:
常に敬iousな心を持っていて、喜んで共有してください。知識はより意味があります。
PS:参照用の2つの非常に便利な統計ツールを次に示します。
オンラインワードカウントツール:
http://tools.vevb.com/code/zishutongji
オンライン文字の統計と編集ツール:
http://tools.vevb.com/code/char_tongji
Javaアルゴリズムの詳細については、このサイトに興味のある読者は、「Javaデータ構造とアルゴリズムのチュートリアル」、「Java操作DOMノードのヒントの要約」、「Javaファイルの要約およびディレクトリ操作のヒント」、「Java Cache操作のヒントの要約」というトピックを見ることができます。
この記事がみんなのJavaプログラミングに役立つことを願っています。