In this article, we will discuss the concept of the C++ code: Count Number of spaces of the given string
In this post, we are going to learn how to count the number of spaces in the given string in C++ programming language
The program allows the user to enter a String and then it counts the number of white space in the given string using for loop in C++ programing language
Program 1
#include <iostream> #include <conio.h> #include <stdio.h> using namespace std; int main() { char str[100]; int i; int space=0; cout<<"Enter a string\n"; gets(str); for(i=0; i<=str[i]; i++){ if(str[i]==' '){ space++; } } cout<<"Total white space :"<<space; getch(); return 0; }
When the above code is executed, it produces the following result
Enter a string C++ is an OOP supported language Total white space: 5
The program allows the user to enter a String and then it counts the white space in the given string using while loop in C++ programing language
Program 2
#include <iostream> #include <conio.h> #include <stdio.h> using namespace std; int main() { char str[100]; int i; int space=0; cout<<"Enter a string\n"; gets(str); i=0; while(i<=str[i]){ if(str[i]==' '){ space++; } i++; } cout<<"Total white space :"<<space; getch(); return 0; }
When the above code is executed, it produces the following result
Enter a string C and C++ are procedural languages Total white space: 5
The program allows the user to enter a String and then it counts the white spaces in the given string using do-while loop in C++ programing language
Program 3
#include <iostream> #include <conio.h> #include <stdio.h> using namespace std; int main() { char str[100]; int i; int space=0; cout<<"Enter a string\n"; gets(str); i=0; do{ if(str[i]==' '){ space++; } i++; } while(i<=str[i]); cout<<"Total white space :"<<space; getch(); return 0; }
When the above code is executed, it produces the following result
Enter a string This is a string Total white space: 3
Approaches
Suggested for you
Similar post
C++ program to count the total number of characters in the given string
C program to count the total number of characters in the given string
Python program to count the total number of characters in the given string
Java program to count the total number of vowels and consonants digits special characters and spaces
C program to count the total number of vowels and consonants digits special characters and spaces
C++ program to count the total number of vowels and consonants digits special characters and spaces
Python code to Calculate sum of odd and even in a list In this tutorial,…
How to find reverse number using method In this article, we will discuss the concept…
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…