从命令行上输入一组字符,输出各个字母的有多少
请输入字符串:
hello world gamecolloege
结果:
h 1
e 4
l 5
o 4
等等
请问这里该怎么做最好,最快,用switch来判断是在太慢了!
请输入字符串:
hello world gamecolloege
结果:
h 1
e 4
l 5
o 4
等等
请问这里该怎么做最好,最快,用switch来判断是在太慢了!
解决方案 »
- 判断一个n*n矩阵是不是拉丁方~
- 直线坐标求解..!!
- 散分贴,关于interface和Object关系的思考!
- 请高手叫我将JRE和程序一起打包的方法,要求JRE删减到最小。
- 求一非常简单的JAVA操作数据库代码
- 谁能解释一下java io里的字节流和字符流究竟有什么具体的区别。
- java 程序与外部程序交互的问题
- ORACLE JDBC驱动如何选择
- 读取sybase数据库中数据出现乱码的问题如何解决?
- 多线程编程 java.lang.IllegalMonitorStateException at java.lang.Object.wait
- 请教,怎样用java实现文件备份
- 使用AWT,创建一个TextField类的对象,如何实现文本的对齐方式?
public static void main(String[] args) {
// TODO code application logic here
String str="ABabcdefgxyzXYZ";
int len=str.length();
int a[]=new int[200];
char ch;
for (int i=0;i<len;i++){
ch=str.charAt(i);
a[(int)ch]++;
}
for (int i=65;i<=200;i++){
ch=(char)i;
if (a[i]>0) System.out.println(ch+":"+a[i]);
}
}
}我就不讲解了,呵呵,能跑,调试过了
用charAt()得到一个字母,和字母数组比较,用indexOf()查找,如果没有找到的话会返回-1,
如果没有找到的话,把这个字母存入字母数组,对应的(相同)字母个数数组中初始化为1。
如果找到了,返回index,把对象的字母个数数组中的数字加1。大概就是这个样子:
tmpChar = args[i].charAt(j);
tmpIndex=indexOf(tChar);
if(tmpIndex!=-1)
count[tmpIndex-]+=1;
else
later[index-1]=tChar;
count[index-1]=1;
index++;
import java.util.Iterator;public class Exercise { public static void main(String[] args) {
HashMap map = getCharMount(args[0]); //打印结果
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object ch = it.next();
System.out.println(ch + " " + map.get(ch));
}
} /**
* 将字符串str中的字符及其出现的次数存入HashMap
*/
public static HashMap getCharMount(String str) {
HashMap map = new HashMap();
for (int i = 0; i < str.length(); i++) {
Character ch = new Character(str.charAt(i));
Integer tmp = (Integer) map.get(ch);
if (tmp == null)
map.put(ch, new Integer(1));
else
map.put(ch, new Integer((tmp.intValue() + 1)));
}
return map;
}
}