Home Blog Tools Contact

How to Count Characters in Java?


The most common method used in java to count the characters in a string is the length() method. The below example shows the way to count all the characters in a string including whitespaces.

Example - 01

1
2
3
4
5
6
7
class CountCharactersInString {
	public static void main(String[] args) {
		String str = "This is a sample string";
		int len = str.length();
		System.out.println("Length of the String: " + len);
	}
}

Output:

Length of the String: 23

Explanation

In Java, the length() function is used to count the characters in a string. Here, when we use the length() function with the given string str, it will return the count as the output.

Character - An Introduction

Character means a single object used to represent text, numbers, symbols, or special characters. For example, the letter 'a' is considered a single character, and the word "java" is considered a string with 4 characters.

In Java, the char keyword is commonly used to represent the characters. This char is the data type of java and it is used to store a single character. Single quotes should surround the char value. String in java means, zero or more characters. Double quotes should surround the string value. The below code shows the way to declare characters and strings in java.

Example - 02

1
2
3
4
5
6
7
8
class Example2 { 
	public static void main(String[] args) {  
		char char1='A';  
	   String str = "Hello";
		System.out.println("Character: " + char1); 
		System.out.println("String: " + str);              
	}         
} 

Output

Character: A

String: Hello

ASCII for the Characters - An Introduction

American Standard Code for Information Interchange(ASCII) is containing 128 characters including numbers (0 - 9), English letters (A - Z including upper case, and lower case), special characters, and white spaces. Each character is referred to by a numeric ASCII value.

  • The ASCII value of "A" is 65
  • The ASCII value of "a" is 97
  • The ASCII value of "0" is "0"
  • The ASCII value of "@" is 64

Java has methods to convert characters to ASCII or ASCII to character. See the example below.

Example-03

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ASCIIChars {
	public static void main(String[] args) {
		char char1 = 'a';
	   int char2ASCII = 65;
		System.out.println("Character a: " + char1);
		System.out.println("ASCII for a: " + (int)char1);
		System.out.println("ASCII for A: " + char2ASCII );
		System.out.println("Character A: " + (char)char2ASCII);
	}
}

Output:

Character a: a

ASCII for a: 97

ASCII for A: 65

Character A: A

How to count characters without white spaces in Java?

If we need to count only the characters without the whitespaces, then we can iterate over the string and count the characters. The example below shows how to count only the characters in a given string.

Example - 04

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class CountNonWhiteSpaceCharacters {
	public static void main(String[] args) {
		String str = "This is a sample string";
	   int count = 0;
	  //count each characters except spaces
	  for(int i=0; i < str.length(); i++) {
		if(str.charAt(i) != ' ')
			count++;
  }
		System.out.println("Length of the String: " + count);
	}
}

Output:

Length of the String: 19

Code complexity

  • Runtime complexity: O(n)
  • Space complexity: O(1)

Explanation

Using the for loop we can iterate over the given string str. Then check each character in the string based on the conditions whether the character is a space or not. If the character is not space then we can increment the counter value by one.

The charAt() function in java returns a character at the specified index in a string. We can use loops to iterate over the string and check each character in the string using the charAt() function whether it's a character or whitespace. If the specified character is not whitespace then the value of the counter gets incremented. Finally, we can get the output.

How to count special characters in Java?

If we need to count the occurrence of upper-case letters, lower-case letters, numbers, or any specific characters in java, then we need to iterate over the given string and check each character based on the conditions and we can count each occurrence. The below example show the way to count the occurrences.

Example - 05

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class CountSpecialCharacters {
	public static void main(String args[]) {
		String inputString = "Hello@%&World!#123";
 
		int upperCount = 0;
   int lowerCount = 0;
   int numCount = 0;
   int specialCharCount = 0;
 
		//iterate over the string
		for(int i = 0; i < inputString .length(); i++) {
			char ch = inputString .charAt(i);
			if(ch >= 'A' && ch <= 'Z')
				upperCount++;
			else if(ch >= 'a' && ch <= 'z')
				lowerCount++;
			else if(ch >= '0' && ch <= '9')
				numCount++;
			else
				specialCharCount++;
		}
  System.out.println("Lowercase Count: " + lowerCount);
  System.out.println("Uppercase Count: " + upperCount );
  System.out.println("Numbers Count: " + numCount );
  System.out.println("Special Characters  Count: " + specialCharCount);
	}
}

Output

Lowercase Count: 8

Uppercase Count: 2

Numbers Count: 3

Special Characters Count: 5

Code complexity

  • Runtime complexity: O(n)
  • Space complexity: O(1)

Explanation

We need to declare some variables to count the upper-case letters, lower-case letters, numbers, and special characters. Then using the loop we can iterate through the given string and check each character based on the conditions whether that specific character is an upper-case or lower-case or number and increment the relevant counters by one. If the character is not included under these conditions, then that character is considered a special character. Finally, we can print each variable to get the output.

How to count the occurrence of a specific character in java?

If we have to count the occurrence of a specific character in a given string, then iterate throughout the length of the string and check whether each character in the string matches the character to search. The below example shows the way to count the occurrence.

Example - 06

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class CountOccurencesOfCharacter {
  public static void main(String args[]) {
	  
	String inputString = "Hello World";
	char searchChar = 'l';   
  
	int count=0;
	for(int i=0; i<inputString .length(); i++) {
			if(inputString .charAt(i) == searchChar)
			count++;
	}
  
	System.out.println("The Occurrence of Character ("+searchChar +") is: "+count);
	 }
}

Output

The Occurrence of Character (l) is: 3

Code complexity

  • Runtime complexity: O(n)
  • Space complexity: O(1)

Explanation

We have to use a loop to iterate over the given string and check each character with the character we need to count the occurrence. If any matches are found, we can increment the counter value by one. Finally, we can print that counter variable to get the output.

How to count the occurrence of characters in java?

If we need to count the occurrence or frequency of each character in a given string, then we can use the following method.

Example - 07

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class CountOccurrence {  
	 public static void main(String[] args) {  
		String str = "Hello World";  
		int[] arr = new int[str.length()];  
		int i, j;  
		  
		//Converts given string into character array  
		char chr[] = str.toCharArray();
		for(i = 0; i <str.length(); i++) {  
			arr[i] = 1;  
			for(j = i+1; j <str.length(); j++) {  
				if(chr[i] == chr[j]) {  
					arr[i]++; 
					chr[j] = '0'; //masking to avoid recount
				}  
			}  
		}  
		 
		System.out.println("Occurrences  of each character in the string: ");  
		for(i = 0; i <arr.length; i++) {  
			if(chr[i] != ' ' && chr[i] != '0')  
				System.out.println(chr[i] + "-" + arr[i]);  
		}  
	}  
} 

Output

Occurrences of each character in the string:

H-1

e-1

l-3

o-2

W-1

r-1

d-1

Code complexity

  • Runtime complexity: O(n ^ 2)
  • Space complexity: O(n)

Explanation

Define an array with the same size as the string. This array will be used to maintain the count of each character in the string. Then, iterate throughout the string to compare each character with the rest of the characters in the string. If matches are found, increment the count of the corresponding element in the newly defined array. Finally iterate through that array to display the occurrences of characters. In this approach, the algorithm iterates over the given string two times in a nested way ( n -> n ), So the runtime complexity will be O(n * n) = O(n ^ 2)

How to efficiently count the occurrence of characters in java?

We can optimize the above occurrence counter code by introducing a HashMap. The advantage of using hashmap is less runtime and more efficiency as it iterates over the string only one time, and store the occurrence count in HashMap.

  • Iterates over the string = O(n)
  • HashMap contains() check runtime complexity = O(1) Constant
  • HashMap put() runtime complexity = O(1) Constant

The below code explains the way to use the hashmap.

Example - 08

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;
class OccurenceOfCharInString {
	public static void main(String[] args)
	{
		String str = "Hello World";
		HashMap<Character, Integer> countCharMap
			= new HashMap<Character, Integer>();
 
		char[] strArray = str.toCharArray();
		for (char c : strArray) {
			if(countCharMap.containsKey(c)) {
				countCharMap.put(c, countCharMap.get(c) + 1);
			}
			else {
				  countCharMap.put(c, 1);
			}
		}
 
		for (Map.Entry entry : countCharMap.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}
}

Output

H-1

e-1

l-3

o-2

W-1

r-1

d-1

Code complexity

  • Runtime complexity: O(n)
  • Space complexity: O(n)

Explanation

We need to declare the hashmap first. Then we need to traverse or iterate the given string and check whether the hashmap already contains the traversed character or not. If the Hashmap contains the character, then increment the count using get() and put() methods in the Hashmap. Once the traversal is completed, then traverse the hashmap and display the characters and the occurrence.