Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Count Spaces in a Java String

$
0
0

1. Overview

When we work with Java strings, sometimes we would like to count how many spaces are in a string.

There are various ways to get the result. In this quick tutorial, we'll see how to get it done through examples.

2. The Example Input String

First of all, let's prepare an input string as the example:

String INPUT_STRING = "  This string has nine spaces and a Tab:'	'";

The string above contains nine spaces and a tab character wrapped by single quotes. Our goal is to count space characters only in the given input string.

Therefore, our expected result is:

int EXPECTED_COUNT = 9;

Next, let's explore various solutions to get the right result.

We'll first solve the problem using the Java standard library, then we'll solve it using some popular external libraries.

Finally, in this tutorial, we'll address all solutions in unit test methods.

3. Using Java Standard Library

3.1. The Classic Solution: Looping and Counting

This is probably the most straightforward idea to solve the problem.

We go through all the characters in the input string. Also, we maintain a counter variable and increment the counter once we see a space character.

Finally, we'll get the count of the spaces in the string:

@Test
void givenString_whenCountSpaceByLooping_thenReturnsExpectedCount() {
    int spaceCount = 0;
    for (char c : INPUT_STRING.toCharArray()) {
        if (c == ' ') {
            spaceCount++;
        }
    }
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.2. Using Java 8's Stream API

Stream API has been around since Java 8.

Additionally, since Java 9, a new chars() method has been added to the String class to convert the char values from the String into an IntStream instance.

If we're working with Java 9 or later, we can combine the two features to solve the problem in a one-liner:

@Test
void givenString_whenCountSpaceByJava8StreamFilter_thenReturnsExpectedCount() {
    long spaceCount = INPUT_STRING.chars().filter(c -> c == (int) ' ').count();
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.3. Using Regex's Matcher.find() Method

So far, we've seen solutions that count by searching the space characters in the given string. We've used character == ‘ ‘ to check if a character is a space character.

Regular Expression (Regex) is another powerful weapon to search strings, and Java has good support for Regex.

Therefore, we can define a single space as a pattern and use the Matcher.find() method to check if the pattern is found in the input string.

Also, to get the count of spaces, we increment a counter every time the pattern is found:

@Test
void givenString_whenCountSpaceByRegexMatcher_thenReturnsExpectedCount() {
    Pattern pattern = Pattern.compile(" ");
    Matcher matcher = pattern.matcher(INPUT_STRING);
    int spaceCount = 0;
    while (matcher.find()) {
        spaceCount++;
    }
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

3.4. Using the String.replaceAll() Method

Using the Matcher.find() method to search and find spaces is pretty straightforward. However, since we're talking about Regex, there can be other quick ways to count spaces.

We know that we can do “search and replace” using the String.replaceAll() method.

Therefore, if we replace all non-space characters in the input string with an empty string, all spaces from the input will be the result.

So, if we want to get the count, the length of the resulting string will be the answer. Next, let's give this idea a try:

@Test
void givenString_whenCountSpaceByReplaceAll_thenReturnsExpectedCount() {
    int spaceCount = INPUT_STRING.replaceAll("[^ ]", "").length();
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

As the code above shows, we have just one line to get the count.

It's worthwhile to mention that, in the String.replaceAll() call, we've used the pattern “[^ ]” instead of “\\S”. This is because we would like to replace non-space characters instead of just the non-whitespace characters.

3.5. Using the String.split() Method

We've seen that the solution with the String.replaceAll() method is neat and compact. Now, let's see another idea to solve the problem: using the String.split() method.

As we know, we can pass a pattern to the String.split() method and get an array of strings that split by the pattern.

So, the idea is, we can split the input string by a single space. Then, the count of spaces in the original string will be one less than the string array length.

Now, let's see if this idea works:

@Test
void givenString_whenCountSpaceBySplit_thenReturnsExpectedCount() {
    int spaceCount = INPUT_STRING.split(" ").length - 1;
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

4. Using External Libraries

Apache Commons Lang 3 library is widely used in Java Projects. Also, Spring is a popular framework among Java enthusiasts.

Both libraries have provided a handy string utility class.

Now, let's see how to count spaces in an input string using these libraries.

4.1. Using the Apache Commons Lang 3 Library

The Apache Commons Lang 3 library has provided a StringUtil class that contains many convenient string-related methods.

To count the spaces in a string, we can use the countMatches() method in this class.

Before we start using the StringUtil class, we should check if the library is in the classpath. We can add the dependency with the latest version in our pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Now, let's create a unit test to show how to use this method:

@Test
void givenString_whenCountSpaceUsingApacheCommons_thenReturnsExpectedCount() {
    int spaceCount = StringUtils.countMatches(INPUT_STRING, " ");
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

4.2. Using Spring

Today, a lot of Java projects are based on the Spring framework. So, if we're working with Spring, a nice string utility provided by Spring is already ready to use: StringUtils.

Yes, it has the same name as the class in Apache Commons Lang 3. Moreover, it provides a countOccurrencesOf() method to count the occurrence of a character in a string.

This is exactly what we're looking for:

@Test
void givenString_whenCountSpaceUsingSpring_thenReturnsExpectedCount() {
    int spaceCount = StringUtils.countOccurrencesOf(INPUT_STRING, " ");
    assertThat(spaceCount).isEqualTo(EXPECTED_COUNT);
}

5. Conclusion

In this article, we've addressed different approaches to counting space characters in an input string.

As always, the code for the article can be found over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>