package com.test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入字符串:"); String s= sc.nextLine(); //String s = "Hello World My First Unit Test"; String[] str =s.split(" "); Map map = new HashMap<String, String>(); for (int i = 0; i < str.length; i++) { //System.out.println(str[i]); if(map.containsKey(str[i])){ String value = (String) map.get(str[i]); int a = Integer.parseInt(value) + 1; String value1 = String.valueOf(a); map.remove(str[i]); map.put(str[i], value1); } else{ map.put(str[i], "1"); } } Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println(entry.getKey()+ " " + entry.getValue()); } } }
package com.test; import java.util.Scanner; public class demo2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入字符串:"); String s= sc.nextLine(); //String s = "how are you"; String[] str = s.split(" "); StringBuffer ss = new StringBuffer(); for (int i = str.length-1; i >=0; i--) { //System.out.println(str[i]); ss.append(str[i] + " "); } System.out.println("new: "+ss); } }