文字列にある語が何回出現しているか数える 2007/06/25

文字列にある語が何回出現しているか数える


正規表現使うというのありだと思うけども。


package t;

import java.util.HashMap;
import java.util.Map;

public class Test3 {

public static void main(String[] args) {

String s = "こんにちわabcこんにちわ こんにちわ";

Map<String, Integer> map = p(s);
System.out.println(map.get("こんにちわ"));
}

public static Map<String, Integer> p(String s) {
Map<String, Integer> map = new HashMap<String, Integer>();
int len = s.length();

for (int i = 0; i < len; i++) {
String tmp = s.substring(i);
for (int j = 1; j <= tmp.length(); j++) {
String tmp2 = tmp.substring(0, j);
System.out.println(tmp2);
Integer cnt = map.get(tmp2);
cnt = cnt == null ? 1 : (cnt + 1);
map.put(tmp2, cnt);

}
}
System.out.println(map);
System.out.println("==================");
return map;
}
}

: