Find duplicate characters in a String and count the number of occurances using Java

前端 未结 30 2531
遇见更好的自我
遇见更好的自我 2020-12-14 11:47

How can I find the number of occurrences of a character in a string?

For example: The quick brown fox jumped over the lazy dog.

Some example

30条回答
  •  半阙折子戏
    2020-12-14 12:26

    Using Eclipse Collections CharAdapter and CharBag:

    CharBag bag = 
        Strings.asChars("The quick brown fox jumped over the lazy dog.").toBag();
    
    Assert.assertEquals(1, bag.occurrencesOf('a'));
    Assert.assertEquals(4, bag.occurrencesOf('o'));
    Assert.assertEquals(8, bag.occurrencesOf(' '));
    Assert.assertEquals(1, bag.occurrencesOf('.'));
    

    Note: I am a committer for Eclipse Collections

提交回复
热议问题