获取字符串中的所有字符及其编号

发布于 2024-09-03 12:05:45 字数 95 浏览 4 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一绘本一梦想 2024-09-10 12:05:45

只需绘制每个字符及其计数的映射即可。您可以使用 String#toCharArray() 并使用 增强的 for 循环。在每次迭代中,从映射中获取计数,如果不存在则设置它,然后将其增加 1 并放回映射中。非常简单。

下面是一个基本的启动示例:

String string = "I am really busy right now";
Map<Character, Integer> characterCounts = new HashMap<Character, Integer>();
for (char character : string.toCharArray()) {
    Integer characterCount = characterCounts.get(character);
    if (characterCount == null) {
        characterCount = 0;
    }
    characterCounts.put(character, characterCount + 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 using String#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:

String string = "I am really busy right now";
Map<Character, Integer> characterCounts = new HashMap<Character, Integer>();
for (char character : string.toCharArray()) {
    Integer characterCount = characterCounts.get(character);
    if (characterCount == null) {
        characterCount = 0;
    }
    characterCounts.put(character, characterCount + 1);
}

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.

不甘平庸 2024-09-10 12:05:45

是家庭作业吗?在不知道的情况下,我会尽力回答。

你的问题背后的逻辑是

  • 遍历列表中的一个字符,一次
  • 计算该字符:由于可能的字符(不包括 unicode)只有 256 个,你可以拥有一个 256 个 int 的数组并在那里计算它们:这样您就不需要搜索正确的计数器,而只需增加正确的索引即可。

Is it homework? Without knowing it I'll assume a best-effort answer.

The logic behind your problem is to

  • go trought the list one character at time
  • count that character: since possible characters (excluding unicode) are just 256 you can have an array of 256 ints and count them there: in this way you won't need to search the correct counter but just increment the right index.
跨年 2024-09-10 12:05:45

我不确定你的确切需求,但似乎你想计算出现次数,无论大小写,也许还忽略空格等字符。所以你可能想要这样的东西:

String initial = "I   am really   busy  right now";

String cleaned = initial.replaceAll("\\s", "") //remove all whitespace characters
        .toLowerCase(); // lower all characters

Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char character : cleaned.toCharArray()) {
    Integer count = map.get(character);
    count = (count!=null) ? count + 1 : 1;
    map.put(character, count);
}

for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

调整正则表达式以满足你的确切要求(以跳过标点符号等)。

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:

String initial = "I   am really   busy  right now";

String cleaned = initial.replaceAll("\\s", "") //remove all whitespace characters
        .toLowerCase(); // lower all characters

Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char character : cleaned.toCharArray()) {
    Integer count = map.get(character);
    count = (count!=null) ? count + 1 : 1;
    map.put(character, count);
}

for (Map.Entry<Character, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Tweak the regex to meet your exact requirements (to skip punctuation, etc).

爱冒险 2024-09-10 12:05:45
        String input = "AAZERTTYAATY";
        char[] chars = input.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char aChar : chars) {
            Integer charCount = map.putIfAbsent(aChar, 1);
            if (charCount != null) {
                charCount++;
                map.put(aChar, charCount);
            }
        }
        String input = "AAZERTTYAATY";
        char[] chars = input.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char aChar : chars) {
            Integer charCount = map.putIfAbsent(aChar, 1);
            if (charCount != null) {
                charCount++;
                map.put(aChar, charCount);
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文