首先是单词分析:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.junit.Test; public class Word { @Test public void testAnalyse() { String str = "Hello World My First Unit Test Test"; analyse(str); } /** * 用于分析字符串单词频率,并输出 * @param str */ public void analyse(String str) { String[] array = str.split(" "); Map<String, Integer> map = new HashMap<String, Integer>(); int n; //临时记录单词出现频率 for (String s : array) { if (map.get(s) == null) { map.put(s, 1); //如果没出现过单词,就初始化1给这个单词 } else { n = map.get(s); //先保存 map.remove(s); map.put(s, n+1); } } Iterator<Entry<String, Integer>> mapIt = map.entrySet().iterator(); while (mapIt.hasNext()) { Entry<String, Integer> entry = mapIt.next(); //取出每一个实体 System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
其次是句子回转:
import org.junit.Test; public class Sentence { @Test public void reverse() { String str = "aoteman"; String newStr = ""; for (int i = 0; i < str.length(); i++){ newStr += str.charAt(str.length() - i - 1); } System.out.println(newStr); // System.out.println(new StringBuffer(str).reverse().toString() ); } }