2016-07-13 3 views
-5

合計を取得する方法は?文字列中の部分文字列の 文字列内のすべての部分文字列。総数を表示する方法文字列内の部分文字列の合計

例:

str="This is this my book is This" 

O/pは以下の好きなはずです。

This-3 
Is=2 
my=1 
book=1 
+1

空白文字を使用して分割します。結果リストを反復し、各結果をマッチさせ、一致するものを数えます。具体的な問題に直面した場合は、ここに戻ってください。そうでなければ、これは "私の宿題をしてください"と思われる。 –

+0

@ jp-jeeこれは最後の1日か2日に見た2番目の質問です。文字列内の単語を数える方法です。彼らはおそらく同じクラスに入っています。 – Aaron

+0

[別個の単語のカウント数]の可能な複製(http://stackoverflow.com/questions/6454348/count-number-of-distinct-words) –

答えて

0

を私が正しい場合は、すべての単語ではなく、すべての可能な部分列の出現を検索したいです。非常に小さく分かりやすいコードは、次のようになります。

// Split at space 
String[] words = input.split(" "); 
HashMap<String, Integer> countingMap = new HashMap<>(); 
for (String word : words) { 
    Integer counter = countingMap.get(word); 
    if (counter == null)) { 
     counter = 0; 
    } 
    countingMap.put(word, counter + 1); 
} 

しかし、このアプローチは、各単語がスペースで囲まれていることを前提としているため制限されています。

Regexは、より強力なツールであり、単語境界の特殊文字を提供します(これも、!、などと一致します)。あなたがここでの例を見ることができます

\b(.+?)\b 

regex101.com/r/hO8kA0/1

Javaでこれを行うには?次のパターンを考えてみましょうか

Pattern pattern = Pattern.compile("\\b(.+?)\\b"); 
Matcher matcher = pattern.matcher(input); 

while(matcher.find()) { 
    String word = matcher.group(1); 
    // Here is your word, count the occurrences like above 
} 
+0

OPはこの問題を試したことさえなく、正直なところ宿題のように見えますが、私は全面的な解決策を提示しません。 http://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions – Adam

0

私が正しくあなたを理解している場合、これはあなたの問題の解決策です:

String str="This is this my book is This"; 
    Map<String, Integer> counts = new HashMap<String, Integer>(); 

    String[] words = str.toLowerCase().split("[\\s\\.,;!\\?]"); 

    for (String word: words) { 
     int count = counts.containsKey(word) ? counts.get(word).intValue() : 0; 
     counts.put(word, Integer.valueOf(count + 1)); 
    } 

あなたはちょうどあなたがマップでの発生を考慮して収集する区切り文字で文字列を分割。

+0

OPはこの問題を試したこともなく、正直なところ宿題のように見えますが、私は全体の解決策を与える。 http://meta.stackexchange.com/questions/10811/how-do-i-ask-and-answer-homework-questions – Adam

+0

さらに、彼にJava 8 Lambdaソリューションを提供してください。グッドラックはそれを信用しようとしています。 – Orin

0
String str="This is this my book is This"; 
String[] words = str.split(" "); 
Map<String,Integer> unitwords = new HashMap<String,Integer>; 
for(String word: words){ 
    if(unitwords.containsKey(word)){ 
    unitwords[word]++; 
    }else{ 
    unitwords.add(word,1); 
} 

地図の単位ワードを印刷します。

関連する問題