Count number of white spaces in string is a simple string based program.
In this tutorial we are going to see white spaces meaning, white spaces in c and program to count number of white spaces in string.
First we will see white spaces in c.
White spaces in c :
In c programming, white spaces is any character series that represents space horizontally or vertically. In ASCII, white space characters are space ( ‘ ‘ ),tab ( ‘\t’ ), carriage return ( ‘\r’ ), newline ( ‘\n’ ), vertical tab ( ‘\v’ ) and form-feed ( ‘\f’ ).
Logic to count number of white spaces in string :
To find a white space. first we take one counter and then we take a input from user a string after that we read the string from start to end. while traversing the string we simultaneously check for spaces ( ‘ ‘ ) in string if space encounter then we increment the counter. at the end after string ends we print the value of counter which is our count to white space..
String = Technical seek website
White spaces in string = 2
Algorithm to count white spaces in string :
2. Declare variables
3. Set one counter to 0
4. Take a input from user
5. Read the string from start to end one by one character.
6. if character is space
7. then increment counter value
8. Print the count for white spaces.
Concept you need to know from c programming :
1. Input and output in c
2. variables and datatype in c
3. Strings in c
4. condition and looping in c
C program to count number of white spaces in string
char str ;
int i, nspace;
printf("Enter a line of text:\n");
i = 0;
while (str[i] != '\0')
char ch= str[i];
if (ch == ' ' || ch =='\n' || ch == '\t')
printf("White spaces in string: %d", nspace);
1 Include header files in program stdio.h
2. Write main function from where the execution of program starts.
3. Declare the variables.
str => to store the string
i => for traversing the loop
nSpace => to store the count for spaces
4. Next take a input from user
Str = A Technical seek website is good
5. Next we need to traverse the string from start to end starting with 0 index so first set value of i =0
then using while loop start reading character from string one by one.
while (str[i] != ‘\0’)
At iteration 1 :
i = 0 , str = A
str != ‘\0’ this condition becomes true and while loop get executed
ch = str => ch=A
if (ch == ‘ ‘ || ch ==’\n’ || ch == ‘\t’) => this will check character is whites pace. out character is A so this if condition skipped and i is incremented.
At iteration 2 :
i = 1, str = ‘ ‘
str != ‘\0′ this condition becomes true and while loop get executed
ch = str => ch=’ ‘
if (ch == ‘ ‘ || ch ==’\n’ || ch == ‘\t’) => this will check character is whites pace. out character is ‘ ‘ so this if condition is executed.
nspace++; => nspace = 1
6. This process continuous till string reached to end.
7. Now we have a count value for white spaces in nspace.
8. Print the white spaces in string.
9. End with the program