HashMap<String,Integer> hm = new HashMap<String,Integer>();
String ss = "好啊abc hello";
for(int i=0;i<ss.length();i++){
String temp = ss.substring(i, i+1);
if(hm.containsKey(temp)){
int j = hm.get(temp);
hm.put(temp, i+1);
}else{
hm.put(temp,1);
}
}System.out.println(hm);
String ss = "好啊abc hello";
for(int i=0;i<ss.length();i++){
String temp = ss.substring(i, i+1);
if(hm.containsKey(temp)){
int j = hm.get(temp);
hm.put(temp, i+1);
}else{
hm.put(temp,1);
}
}System.out.println(hm);
通过统计字母 a-z,A-Z的个数 并以A(1)b(1)c(1)H(1)e(1)l(2)o(1)的 形式打印出来。
int j = hm.get(temp);
hm.put(temp, i+1);hm.put(temp, j+1);
String ss = "好啊abc hello";
for(int i=0;i<ss.length();i++){
char c = ss.charAt(i);
if(!Character.isLetter(c))
continue;
String temp = new String(ss.substring(i,i+1));
if(hm.containsKey(temp)){
int j = hm.get(temp);
hm.put(temp, j+1);
}else{
hm.put(temp,1);
}
}System.out.println(hm);
import java.util.*;class codemap {
/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args) {
// TODO: Add your code here
HashMap <String,Integer> hm = new HashMap <String,Integer>();
String s="好啊abc hello" ;
String s1;
int i,j;
for(i=0;i<s.length();i++)
{
s1=s.substring(i,i+1);
if (s1.equals(" "))
continue;
if (hm.containsKey(s1))
j=hm.get(s1);
else
j=0;
hm.put(s1,j+1);
}
System.out.println(hm);
}
}
if (s1.equals(" "))
continue;
你可用正则表达式,把不要统计的字符去掉
HashMap<String, Integer> hm = new HashMap<String, Integer>();
String ss = "好啊AAbc Hello ABC"; for (int i = 0; i < ss.length(); i++)
{
String temp = ss.substring(i, i + 1);
char test = ss.charAt(i);
if(test>='a' && test<='z' || test>='A' && test<='Z')
{
if (hm.containsKey(temp))
{
int j = hm.get(temp);
hm.put(temp, j + 1);
}
else
{
hm.put(temp, 1);
}
}
}
String print="";
Iterator it = hm.keySet().iterator();
while(it.hasNext())
{
Object obj=it.next();
print = print + obj + "(" + hm.get(obj) + ")";
}
System.out.println(print);
System.out.println(hm);
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;public class Test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub String str = "好啊abc hello";
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (isLetter(ch)) {
String temp = "" + ch;
int count = 0;
if (map.containsKey(temp)) {
count = map.get(temp);
}
map.put(temp, ++count);
}
}
System.out.println(toString(map));
}
public static boolean isLetter(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
return true;
} else {
return false;
}
}
public static String toString(Map<String, Integer> map) {
String result = "";
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Entry me = (Entry)it.next();
result += me.getKey() + "(" + me.getValue() + ")";
}
return result;
}}输出结果:
o(1)a(1)h(1)c(1)l(2)b(1)e(1)