Count spaces & characters other than spaces in a String in Java

An example logic on counting no.of spaces and characters other than spaces in a String in Java.

Example


/* Taken from gowtham.gutha.util.StringOps. Licensed under GNU GPLv2 */
// Import for Scanner class
import java.util.*;
class CountIgnoreSpace
{

public static void main(String args[])
{

// Create Scanner object to take input from command prompt
Scanner s=new Scanner(System.in);

// Take input from the user and store it in st
String st=s.nextLine();

// Initialize the variable count to 0
int count=0;

// Convert String st to char array
char[] c=st.toCharArray();

// Loop till end of string
for(int i=0;i<st.length();i++)

// If character at index 'i' is not a space, then increment count
if(c[i]!=' ') count++;

// Print no.of chars other than spcaes
System.out.println("No.of chars other than spaces are "+count);

// Print no.of spaces
System.out.println("No.of spaces are "+(st.length()-count));

// Simply,
String words[]=st.split(" ");

// Print no.of spaces
System.out.println("No.of spaces, simply "+(words.length-1));

}

}

Output

gowtham gutha gutha gowtham
No.of chars other than spaces are 24
No.of spaces are 3
No.of spaces, simply 3

Note [Last Logic]


The last logic (splitting into words) will be good if the string 'st' does not start/end with space, if it does then, you'll need to write other logic or simply extend this, mostly strings wont start/end up with a space. The above logic works fine, no matter where the space comes. When a string is split into words with help of a space, (in the above example) there are 4 words, so it is clear that there will be 3 words, so (words.length-1) [1 less than the no.of words].

Also see my other posts on Word Count in Java, for counting no.of numbers (digits) in a string see my post Counting no.of digits in a String in Java, count no.of alphabets in a String in Java

No comments: