Map遍历
package org.baojiwenli.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一段字符串:");
String s = input.next();
System.out.println("字符串的总长度:"+s.length());
Map<Character,Integer> result = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(result.get(ch) != null){
result.put(ch,result.get(ch)+1);
}else{
result.put(ch,1);
}
}
for(Map.Entry entry: result.entrySet()){
System.out.println(entry.getKey()+"->"+entry.getValue());
}
System.out.println("字符串总长度(不包括一样的字符):"+result.size());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314140621112.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0MTAyNjc4,size_16,color_FFFFFF,t_70)
传统的For循环遍历+数组
package org.baojiwenli.collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String a = sc.next();
StringConstitute(a);
}
public static void StringConstitute(String str) {
StringBuffer recordType = new StringBuffer();
int[] recordNumber = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
int count = 0;
String medium = str.charAt(i) + "";
if (!recordType.toString().contains(medium)) {
recordType.append(medium);
count++;
for (int j = i + 1; j < str.length(); j++) {
if (medium.equals(str.charAt(j) + "")) {
count++;
}
}
recordNumber[recordType.length()] = count;
}
}
System.out.println("字符串\"" + str + "\"共有" + recordType.length() + "种字符");
for (int i = 0; i < recordType.length(); i++) {
System.out.println("字符\'" + recordType.charAt(i) + "\'共有" + recordNumber[i + 1] + "个");
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314141957286.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0MTAyNjc4,size_16,color_FFFFFF,t_70)