Examples
- Hello World Program in Java (Print Hello World in Java)
- Java Program to Add Two Numbers (Java Sum / Addition)
- Find Greatest of Three Numbers in Java (Largest Number Program)
- Prime Number Program in Java (Code to Check Prime or Not)
- Java Program for Fibonacci Series (Using for, while, recursion, scanner)
- Factorial Program in Java (Find Factorial of a Number in Java)
- How to Find Sum of Digits of a Number in Java?
- How to Reverse a Number in Java? Program & Examples
- How to Swap Two Numbers in Java? Programs With/Without Third Variable
- Even Odd Program in Java (Program to Check Number is Even or Odd)
- Vowel and Consonant Program in Java
- Java Program for Quadratic Equation (Find Roots With 3 Ways)
- Find Frequency of Characters in a String in Java (4 Ways)
- Remove Space from String in Java (Remove Whitespace)
- String Null Check in Java (String is Empty or Null) - 5 Ways
- How to Print String in Java? 6 Methods
- How to Get ASCII Value of Char in Java? Find ASCII Value
Find Frequency of Characters in a String in Java (4 Ways)
Java is a versatile and widely used programming language known for its robust capabilities in handling various tasks, including text processing and manipulation. One common task when working with strings in Java is to find the frequency of a specific character within the string. This operation is essential in many real-world scenarios, such as data analysis, text processing, and encryption algorithms.
In this tutorial, we will learn how to find the frequency of a character in a string in Java. We'll walk you through the steps required to accomplish this task, starting with the basic concepts and gradually building a complete Java program.
Importance of Finding Characters in a String
The ability to find the frequency of a character in a string holds significant importance in various applications, both within and beyond the realm of software development.
-
Text Analysis: Analyzing textual data is a fundamental part of natural language processing and data science. Counting the occurrence of specific characters or words in a text corpus is crucial for tasks such as sentiment analysis, keyword extraction, and content categorization.
-
Data Validation: When processing user input, it's essential to validate the data to ensure it meets certain criteria. Counting character frequencies can help identify potential issues or anomalies in the input data.
-
String Manipulation: In some cases, you may need to modify strings based on character frequencies. For instance, you might want to replace all occurrences of a specific character with another character or remove it altogether.
-
Cryptography: Frequency analysis is a critical technique in cryptography. It is used to break simple substitution ciphers where characters are replaced with other characters. By counting the frequency of characters in encrypted text, one can make educated guesses about the underlying plaintext.
-
Search Algorithms: Character frequency analysis can be used in search algorithms to optimize the retrieval of relevant documents. By knowing the frequency of certain keywords or characters, search engines can rank search results more effectively.
So, let’s get started and write a Java program to find frequency of a character in a string.
Concepts to Learn:
Find Frequency of Character in String Using for Loop
Here's a Java program to find the frequency of a character in a string using a loop:
Code
simport java.util.Scanner;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to find its frequency: ");
char targetChar = scanner.next().charAt(0);
int frequency = 0;
for (int i = 0; i < inputString.length(); i++) {
if (inputString.charAt(i) == targetChar) {
frequency++;
}
}
System.out.println("Frequency of '" + targetChar + "' in the string is: " + frequency);
}
}
Output
Enter a string: Tutorials Freak
Enter a character to find its frequency: t
Frequency of 't' in the string is: 1
Explanation
-
We start by taking input from the user for the string and the character to find the frequency of.
-
In this example, we enter "Tutorials Freak" as the string and 't' as the character to find.
-
We initialize a variable frequency to zero, which will be used to store the frequency of the target character.
-
Next, we use the Java for loop to iterate through each character of the input string.
-
Inside the loop, we check if the current character in the string is equal to the target character. If they match, we increment the frequency variable.
-
After the loop completes, we print the frequency of the target character in the input string.
In this example, the character 't' appears once in the string "Tutorials Freak", so the program correctly calculates and prints a frequency of 1 for 't'.
Java Program to Find Frequency of Character in a String Using Streams
Here's a program to find the frequency of a character in a string using Java Streams:
Code
import java.util.Scanner;
import java.util.stream.IntStream;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to find its frequency: ");
char targetChar = scanner.next().charAt(0);
long frequency = inputString.chars().filter(ch -> ch == targetChar).count();
System.out.println("Frequency of '" + targetChar + "' in the string is: " + frequency);
}
}
Output
Enter a string: Tutorials Freak
Enter a character to find its frequency: a
Frequency of 'a' in the string is: 2
Explanation
-
We start by taking input from the user for the string and the character to find the frequency of.
-
In this example, we enter "Tutorials Freak" as the string and 'a' as the character to find.
-
We use the chars() method to convert the input string into an IntStream of characters.
-
Then, we use the filter method to filter out only the characters that match the target character ('a' in this case).
-
We count the filtered characters using the count method, which gives us the frequency of the target character.
-
Finally, we print the frequency of the target character in the input string.
Frequency of Character in a String in Java Using HashMap
Here's a Java program to find the frequency of a character in a string using a HashMap:
Code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to find its frequency: ");
char targetChar = scanner.next().charAt(0);
// Create a HashMap to store character frequencies
Map < Character, Integer > charFrequencyMap = new HashMap<>();
// Count character frequencies
for (char ch : inputString.toCharArray()) {
charFrequencyMap.put(ch, charFrequencyMap.getOrDefault(ch, 0) + 1);
}
// Get the frequency of the target character
int frequency = charFrequencyMap.getOrDefault(targetChar, 0);
System.out.println("Frequency of '" + targetChar + "' in the string is: " + frequency);
}
}
Output
Enter a string: Learn Java With Tutorials Freak
Enter a character to find its frequency: a
Frequency of 'a' in the string is: 5
Explanation
-
We start by taking input from the user for the string and the character to find the frequency of.
-
In this example, we enter "Learn Java With Tutorials Freak" as the string and 'a' as the character to find.
-
We create a HashMap called charFrequencyMap to store the frequencies of each character in the input string.
-
We then iterate through each character of the input string using a for-each loop in Java.
-
Inside the loop, we use the getOrDefault method to retrieve the current frequency of the character from the charFrequencyMap. If the character is not yet in the map, we default its frequency to 0.
-
We increment the retrieved frequency by 1 and put it back in the map.
-
After counting all the characters, we retrieve the frequency of the target character ('a' in this case) from the charFrequencyMap.
-
Finally, we print the frequency of the target character in the input string.
Frequency of Character in a String Using RegEx
Here's a Java program to find the frequency of a character in a string using regular expressions:
Code
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter a character to find its frequency: ");
char targetChar = scanner.next().charAt(0);
// Use regular expression to match the target character in the string
String regex = String.valueOf(targetChar);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
int frequency = 0;
while (matcher.find()) {
frequency++;
}
System.out.println("Frequency of '" + targetChar + "' in the string is: " + frequency);
}
}
Output
Enter a string: Best Java Programming Tutorial
Enter a character to find its frequency: a
Frequency of 'a' in the string is: 4
Explanation
-
We start by taking input from the user for the string and the character to find the frequency of.
-
In this example, we enter "Best Java Programming Tutorial" as the string and 'a' as the character to find.
-
We use a regular expression to match the target character ('a') in the input string. The regex is created using String.valueOf(targetChar).
-
We compile the regular expression pattern using Pattern.compile(regex).
-
We create a Matcher object by applying the pattern to the input string using matcher(inputString).
-
We initialize a variable frequency to zero to keep track of the character's frequency.
-
We use a while loop in Java to repeatedly find occurrences of the target character in the input string using matcher.find(). Each time a match is found, we increment the frequency variable.
-
After the loop, we print the frequency of the target character in the input string.
Learn Next: