如何在字符串中获取不同的字符及其数量
这道题可以拆解为两个步骤,第一步,找出不同的字符,第二步,统计出它们的数量。好像有点废话,是不是?那我先来一个答案吧。
public class distinctcharscount { public static void main(string[] args) { printdistinctcharswithcount(itwanger); printdistinctcharswithcount(chenmowanger); } private static void printdistinctcharswithcount(string input) { map<character, integer> charswithcountmap = new linkedhashmap<>(); for (char c : input.tochararray()) { integer oldvalue = charswithcountmap.get(c); int newvalue = (oldvalue == null) ? 1 : integer.sum(oldvalue, 1); charswithcountmap.put(c, newvalue); } system.out.println(charswithcountmap); } }
程序输出的结果是:
{i=1, t=1, w=1, a=1, n=1, g=1, e=1, r=1} {c=1, h=1, e=2, n=2, m=1, o=1, w=1, a=1, g=1, r=1}
说一下我的思路:
1)声明一个 linkedhashmap,也可以用 hashmap,不过前者可以保持字符串拆分后的顺序,结果看起来更一目了然。
为什么要用 map 呢?因为 map 的 key 是不允许重复的,刚好可以对重复的字符进行数量的累加。
2)把字符串拆分成字符,进行遍历。
3)如果 key 为 null 的话,就表明它的数量要 +1;否则的话,就在之前的值上 +1,然后重新 put 到 map 中,这样就覆盖了之前的字符数量。
思路很清晰,对不对?忍不住给自己鼓个掌。
那,jdk 8 之后,map 新增了一个很厉害的方法 merge(),一次性为多个键赋值:
private static void printdistinctcharswithcountmerge(string input) { map<character, integer> charswithcountmap = new linkedhashmap<>(); for (char c : input.tochararray()) { charswithcountmap.merge(c, 1, integer::sum); } system.out.println(charswithcountmap); }
有没有很厉害?一行代码就搞定。第一个参数为键,第二个参数为值,第三个参数是一个 bifunction,意思是,如果键已经存在了,就重新根据 bifunction 计算新的值。
如果字符是第一次出现,就赋值为 1;否则,就把之前的值 sum 1。
以上就是java如何在字符串中获取不同的字符及其数量的详细内容。