获取字符串中的所有字符及其编号
在Java中如何获取字符串中出现的所有字符的列表及其出现次数?假设我们有一个字符串“我现在真的很忙”,所以我应该得到:
i-2、a-2、r-2、m-1 等等。
How in Java can I get list of all characters appearing in string, with number of their appearances ? Let's say we have a string "I am really busy right now" so I should get :
i-2, a-2, r-2, m-1 and so on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需绘制每个字符及其计数的映射即可。您可以使用
String#toCharArray()
并使用 增强的 for 循环。在每次迭代中,从映射中获取计数,如果不存在则设置它,然后将其增加 1 并放回映射中。非常简单。下面是一个基本的启动示例:
要了解有关地图的更多信息,请查看 Sun关于该主题的教程。
您评论说这是“针对一个项目”,但它是一个典型的家庭作业问题,因为它非常基础,并且在一本不错的 Java 书籍/教程的第一章中进行了介绍。如果您是 Java 新手,我建议您阅读涵盖基础知识的 Sun Trails。
Just have a mapping of every character and their counts. You can get the character array of a
String
usingString#toCharArray()
and loop through it using the enhanced for loop. On every iteration, get the count from the mapping, set it if absent and then increment it with 1 and put back in map. Pretty straightforward.Here's a basic kickoff example:
To learn more about maps, check the Sun tutorial on the subject.
You commented that it's "for a project", but it's however a typical homework question because it's pretty basic and covered in the first chapters of a decent Java book/tutorial. If you're new to Java, I suggest to get yourself through the Sun Trails Covering the Basics.
是家庭作业吗?在不知道的情况下,我会尽力回答。
你的问题背后的逻辑是
Is it homework? Without knowing it I'll assume a best-effort answer.
The logic behind your problem is to
int
s and count them there: in this way you won't need to search the correct counter but just increment the right index.我不确定你的确切需求,但似乎你想计算出现次数,无论大小写,也许还忽略空格等字符。所以你可能想要这样的东西:
调整正则表达式以满足你的确切要求(以跳过标点符号等)。
I'm not sure of your exact needs but it seems you want to count occurrences regardless of the case, maybe also ignore characters such as whitespace, etc. So you might want something like this:
Tweak the regex to meet your exact requirements (to skip punctuation, etc).