计算Java中字符串的出现次数 [英] Count occurrences of strings in Java

查看:560
本文介绍了计算Java中字符串的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个好的类可以计数在java中的特定字符串的出现?我想保留一个名称列表,然后为每个名称创建唯一的电子邮件地址。

Is there a good class that can count the occurrences of specific strings in java? I'd like to keep a list of names and then create unique email addresses for each name. For each occurrence of a last name, I'd like to increment the associated number by one.

例如:如果我有3个姓氏为Smith的人, d像他们的地址是smith1 @(地址),smith2 @(地址)和smith3 @(地址)。我看到一个类地图,但我似乎无法正确初始化。是否有一个类可以用来保存字符串及其出现的列表?

Ex: If I have 3 people with the last name Smith, I'd like their address to be smith1@(Address), smith2@(Address), and smith3@(Address). I saw a class "Map" but I can't seem to initialize it correctly. Is there a class that I can use to keep a list of strings and their occurrences?

推荐答案

地图将是一个可行的数据结构,如果你只是看以计算具有给定姓氏的电子邮件的数量。键将是一个String(最后一个名字),并且值将是一个Integer(出现次数)。

Map would be a viable data structure for this, if you're just looking to count the number of emails with given last names. The key would be a String (the last name), and the value would be an Integer (number of occurrences).

您实例化如下:

Map<String, Integer> nameOccurrences = new HashMap<String, Integer>();

要向地图添加值:

nameOccurrences.put("Smith", 1);

要检查地图中是否有名称:

To check if a name is in the map:

if (nameOccurrences.containsKey("Smith")) { ... }

要从地图中获取值:

Integer occurrences = nameOccurrences.get("Smith");

请注意,具有不同大小写的名称将被视为不同的键。如果你需要忽略大写,你必须做一些事情,把键全部大写,然后再将它们添加到地图。

Note that names with different capitalization would be considered different keys. If you need to ignore capitalization, you'd have to do something like make the keys all uppercase before adding them to the Map.

这篇关于计算Java中字符串的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆