Counting char in string java

Count Occurrences of a Character in Java

A String is simply a sequence of characters. In this tutorial, we will learn the different ways to count the occurrences of a specific character in a String.

Method 1 — Iterative Approach

We will traverse through each character present in the String. If this character matches the one we are looking for, we will increase the count by one. The following code demonstrates this approach.

public static int countChars(String str, char c) < int count = 0; for(int i = 0; i < str.length(); i++) < char currChar = str.charAt(i); if(currChar == c) count += 1; >return count; >

Let’s use this method and check whether it gives desirable output or not.

public static void main(String[] args)

The String is: Java is an awesome language!
Character count of ‘a’: 6
Character count of ‘g’: 2
Character count of ‘e’: 3

Method 2 — Recursion Approach

Recursion won’t be the first thing that comes to mind on seeing this problem. However, we can use recursion to solve this problem. We will use two methods instead of one. The first method will be the recursive one, and the second method invokes the first one. The approach is very similar to the one discussed in the previous section.

public static int countCharsRecur(String str, char c, int idx) < if(idx >= str.length()) return 0; else < int count = 0; if(str.charAt(idx) == c) count = 1; return count + countCharsRecur(str, c, idx + 1); >> public static int countChars(String s, char c)

Let’s use the above methods and view the output.

public static void main(String[] args)

The String is: Java is an awesome language!
Character count of ‘a’: 6
Character count of ‘g’: 2
Character count of ‘e’: 3

Method 3 — Using Java 8 Streams

Java 8 Streams also provide a simple way to count the occurrences of a character in a String. We will first convert the String to an IntStream by using the chars() method. We can also use the codePoints() method instead of chars(). Next, we will use the filter() method with a Lambda expression to filter out all the matching characters. Finally, we will use the count() method that returns the count of elements in the filtered stream.

public class Demo < public static void main(String[] args) < String s = "Java is an awesome language!"; int charCountOfA = (int) s.chars().filter(c ->c == 'a').count(); int charCountOfG = (int) s.chars().filter(c -> c == 'g').count(); int charCountOfE = (int) s.chars().filter(c -> c == 'e').count(); System.out.println("The String is: " + s); System.out.println("Character count of 'a': " + charCountOfA); System.out.println("Character count of 'g': " + charCountOfG); System.out.println("Character count of 'e': " + charCountOfE); > >

The String is: Java is an awesome language!
Character count of ‘a’: 6
Character count of ‘g’: 2
Character count of ‘e’: 3

Method 4 — Using Regular Expressions

Regular Expressions can also solve this problem. However, it is not a good idea to use regular expressions to solve such a simple problem. The code below demonstrates the use of regex for this problem.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo < public static int countChars(String str, char c) < String regex = String.valueOf(c); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); int count = 0; while(matcher.find()) count += 1; return count; >public static void main(String[] args) < String s = "Java is an awesome language!"; int charCountOfA = countChars(s, 'a'); int charCountOfG = countChars(s, 'g'); int charCountOfE = countChars(s, 'e'); System.out.println("The String is: " + s); System.out.println("Character count of 'a': " + charCountOfA); System.out.println("Character count of 'g': " + charCountOfG); System.out.println("Character count of 'e': " + charCountOfE); >>

The String is: Java is an awesome language!
Character count of ‘a’: 6
Character count of ‘g’: 2
Character count of ‘e’: 3

Читайте также:  Getter and setter kotlin

Method 5 — External Libraries

Counting occurrences of a character in a String is so common that many external libraries have built-in functions to do this. Let’s use a few external libraries to solve this problem.

Using Guava Library

The Guava library provides the CharMatcher class that can count the number of occurrences of a given character. First, we will use the static is() method of this class. This method creates a CharMatcher instance to match a specific char. Next, we will use the countIn() method that takes a string as a parameter and returns the count of the character in that String.

import com.google.common.base.CharMatcher; public class Demo < public static void main(String[] args) < String str = "Java is an awesome language!"; CharMatcher cm = CharMatcher.is('a'); //Creating the CharMatcher int charCountOfA = cm.countIn(str); //Counting the occurences System.out.println("The String is: " + str); System.out.println("Character count of 'a': " + charCountOfA); >>

The String is: Java is an awesome language!
Character count of ‘a’: 6

Using Apache Library

The Apache Commons library provides a StringUtils class. This class has a convenient countMatches() method that takes a char and a string as input and returns the count of the character in that String as output.

import org.apache.commons.lang3.StringUtils; public class Demo < public static void main(String[] args) < String s = "Java is an awesome language!"; int charCountOfA = StringUtils.countMatches(s, 'a'); int charCountOfG = StringUtils.countMatches(s, 'g'); int charCountOfE = StringUtils.countMatches(s, 'e'); System.out.println("The String is: " + s); System.out.println("Character count of 'a': " + charCountOfA); System.out.println("Character count of 'g': " + charCountOfG); System.out.println("Character count of 'e': " + charCountOfE); >>

The String is: Java is an awesome language!
Character count of ‘a’: 6
Character count of ‘g’: 2
Character count of ‘e’: 3

Summary

Counting the occurrences of a character in a String is a pretty simple task. We can use core Java to solve this problem iteratively or recursively. Streams can also solve this problem in a single line of code. We can also use Regular Expressions, but they provide a sub-optimal solution.

Читайте также:  Эскейп последовательности си шарп

Источник

How to Count Characters in a String in Java?

While programming in Java, there exist chances that you need to check the total number of characters of the specified string. In such a scenario, you must count the string characters to determine their length. This functionality can also be utilized in several Java applications where it is required to delete unwanted or duplicated characters of a string.

This tutorial will describe the methods to count the characters in strings in Java.

How to Count Characters in a String in Java?

To count the string’s characters, there are some methods listed as follows:

We will now check out each of the above-mentioned methods one by one.

Method 1: Count Characters in a String in Java Using for Loop

Using the “for” loop for counting the characters of a string is the simplest method utilized by programmers. This method will iterate according to the string’s length and count its characters.

Example
In this example, we will count the characters of the string with white spaces. For this purpose, we will create a String type variable named “string” and an integer type variable named “chCount” initialized with value 0:

String string = «Welcome To Linux Hint” ;
System.out.println(» String : » + string);

Then, we will iterate the string until the length of the string using for loop and count the characters “chCount” increment value:

Lastly, we will print the value of the “chCount” variable:

In the defined string, there are 18 characters and three spaces. Therefore, the output displayed “21” as the total number of string characters, including spaces:

Want to try out Java methods for counting characters? Have a look at the below-given sections.

Method 2: Count Characters in a String in Java Using String.length() Method

Another method to count a character in a string is the “length()”. This method belongs to the String class; that’s why it is called using the String class object.

Example
In this example, we will consider two cases:

  • Counting string characters including white spaces
  • Counting string characters without spaces

For the first case, we will create an integer type variable named “newString” that stores the length of the full string by calling the “string.length()” method. This method will count the characters of “newString” including the whitespaces:

int newString = string.length();
System.out.println(“The Characters in the String including spaces: ” + newString);

Now, we will find the count of the characters of a string without spaces. For that, we will call the “replace()” method of the String class with the “length()” method. The replace() method accepts two parameters that will neglect the spaces from the string and returns the count of the characters using the length() method:

Читайте также:  Php error paamayim nekudotayim

int newStrng = string. replace ( » » , «» ) . length ( ) ;
System . out . println ( «The Characters in the String without spaces: » + newStrng ) ;

The output shows the 21 as characters count, including spaces, while without spaces, the count of the character is 18:

Let’s check out the third method!

Method 3: Count Characters in a String in Java Using String.chars.count() Method

The “String.chars().count()” method returns the number of characters present in the string, with white spaces. Additionally, we will use the “filter()” method to count characters without spaces.

Example
In this method, we will count the characters of our “strng” String without spaces by utilizing the “String.chars.filter().count()” method:

Do you only want to count the numbers of a particular character occurrence? Check out the following section!

Method 4: Count Characters in a String in Java Using charAt() Method

In a Java program, the “charAt()” method is used if you want to find the occurrence of a specific character in a string.

Example
In this example, we will check how many times the character “n” appears in the string. For this purpose, we will again use the same string that is used in the above example and create an integer type variable “chCount” initialized with “0”, and a character type variable named “findChar” initialized with character “n”:

Now, we will iterate the string until the full length of the string using “for” loop and match every character with “findChar” that is “n” and increment the count if the added condition is evaluated as true, otherwise move to the next iteration:

Lastly, print the character count:

System.out.println(«The Character ‘» +findChar+ «‘ in the String is ‘» +chCount+ «‘ times»);

The given output states that in the “strng” String, the “n” character occurred two times:

We compiled all the necessary information on how to count the characters in a string in Java.

Conclusion

To count characters in a string in Java, there are different methods: using for loop, charAt() method, String.chars.count() method, and the String.length() method. You can count characters from strings, including spaces, without spaces, and the occurrence of the specific character in a string by using these methods. This tutorial discussed the methods to count characters in a string in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Оцените статью