输入一个字符串,输出每个字符出现的次数,用Java如何实现

2024-11-08 17:14:19
推荐回答(2个)
回答1:

用世神length()方法、charAt方法纯银结合for循做返宴环就行了,

package com.golden.test;

public class TestString {

public static void main(String[] args) {

String str = "你叫神马?我叫Tesson.";

for (int i = 0; i < str.length(); i++) {

char item = str.charAt(i);

System.out.println(item);

}

}

}

回答2:

import java.util.*;

public class Test {

public Map fun(String string){
Map map = new HashMap带扮橡();
for (int i = 0; i <缺姿 string.length(); i++) {
char c = string.charAt(i);
if(null == map.get(c))map.put(c, 1);
else {
int length = map.get(c)+1;
map.put(c, length);
}
}
return map;
}

public static void main(String[] args) {

Test test = new Test();
Map蠢旁 map = test.fun("xsakjnakbashkjnxajkvhkdcnajkxhsjkac");
for (Entry entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}

}
}