Pages

Sunday, January 26, 2020

Java: Count the number of blank characters in a given string

The following code is going to print a message with the number of white spaces in a given sentence.



First, we need to write the name of the procedure: countWhiteSpaces


public static void countWhiteSpaces() {

}


The above procedure is static because only one copy of the object is needed.

Then, we need Scanner, in order for the user to be able to write the sentence on the screen. We will also print indications for the user.

Scanner kb = new Scanner(System.in);
System.out.println("Enter a sentence...");

The kb variable will hold the sentence the user is going to type. We store this information into the String called sentence.

String sentence = kb.nextLine();

We need to count the figure out the length of the sentence, for that we user the .lenght() property.

int senLen = sentence.length();

Also, a variable needs to be initialized for counting the number of white spaces.

int blankSpaces = 0;

In order to check and count the number of white spaces in a sentence we will use a for loop. This is going to start in 0 and will iterate until the length of the sentence. The if statement is going to check whether each character is an empty space or not, and then increase the blankSpace variable.

for (int i = 0; i < senLen; i++) {
     if (sentence.charAt(i) == ' ') {
            blankSpaces++;
     }
}


Finally, we are going to print the result

System.out.println("The number of white spaces in your sentence is: " + blankSpaces);




The final code is going to look like this:


import java.util.Scanner;

public class couSpaces {

public static void main(String[] args) {
// TODO Auto-generated method stub
countWhiteSpaces();
}

public static void countWhiteSpaces() {

Scanner kb = new Scanner(System.in);
System.out.println("Enter a sentence...");

String sentence = kb.nextLine();
int senLen = sentence.length();
int blankSpaces = 0;

for (int i = 0; i <  senLen; i++) {

if (sentence.charAt(i) == ' ') {
blankSpaces++;
}

}

System.out.println("The number of white spaces in your sentence is: " + blankSpaces);
}

}