Java: Counts occurrences of a certain character in a given string
Write a Java program to count occurrences of a certain character in a given string.
Sample Solution:
Main.java Code:
Strings.java Code:
Sample Output:
Input text: My high school, the Illinois Mathematics and Science Academy, showed me that anything is possible and that you're never too young to think big. At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, or Fermilab. After graduating, I attended Stanford for a degree in economics and computer science. ASCII or 16 bits Unicode characters (less than 65,535 (0xFFFF)) examples: replace() based solution: Execution time: 2451480 ns (2 ms) Character 'u' occured 5 time(s) charAt() based solution: Execution time: 40343 ns (0 ms) Character 'u' occured 5 time(s) Java 8, functional-style solution: Execution time: 156518104 ns (156 ms) Character 'u' occured 5 time(s) -------------------------------------- Input text: π I love π you Σ so much π π Including Unicode surrogate pairs examples: replace() based solution: Execution time: 97920 ns (0 ms) Character 'Σ' occured 1 time(s) replace() based solution: Execution time: 403313 ns (0 ms) Character 'π' occured 2 time(s) codePointAt() based solution: Execution time: 31224 ns (0 ms) Character 'Σ' occured 1 time(s) codePointAt() based solution: Execution time: 25059 ns (0 ms) Character 'π' occured 2 time(s) Java 8, functional-style solution: Execution time: 1735086 ns (1 ms) Character 'Σ' occured 1 time(s) Java 8, functional-style solution: Execution time: 41650 ns (0 ms) Character 'π' occured 2 time(s)
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to count how many times a specific character appears in a string using iteration.
- Write a Java program to determine the frequency of a given character in a string using stream operations.
- Write a Java program to calculate the occurrence count of a character without using built-in frequency methods.
- Write a Java program to iterate through each character of a string and count the number of times a target character appears.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous Java Exercise: Concatenate a given string with itself of a given number of times.
Next Java Exercise: Check two consecutive, identical letters in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.