Java count number of spaces in a string
Following java program counts the number of spaces with the help of toCharArray() method of string class. You can easily make this program user define by using scanner class as previous describe.
Java Count Space Example
//How to count number of spaces in java class CountNumberOfSpace{ static String str; static int count(String temp){ str=temp; char ch[] =str.toCharArray(); int flag=0; for(int i=0;i<=ch.length-1;i++){ if(ch[i]==' ') flag+=1; } return flag; } public static void main(String...s){ System.out.print("Number of space are = "); System.out.print(count(" Java Tutorial ")); } }
Output
Number of space are = 10