BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C++ Program to find number of Digits and White Spaces in a String

Last Updated: September 12, 2017 by Chaitanya Singh | Filed Under: C++ Programs

This program takes the input string (entered by user) and counts the number of digits and white spaces in the String.

Example: Program to count number of digits and white spaces in a String

In this program we have a string object to store the input string. If you want you can also use char array in place of string object but the problem with char array is that it has a fixed size, which means if you define a char array of size 100 and user enters string longer than the program will truncate the string.

Here we are using for loop to traverse the string from starting character till end char (‘\0’) and counting the number of digits and white spaces. To understand this program you need to study the for loop and strings topics of C++ Programming.

#include <iostream>
using namespace std;
int main(){
   string str;
   int digitCounter = 0, spaceCounter = 0;
   cout << "Enter any string: ";
   getline(cin, str); 
   //'\0 represent end of string
  for(int i = 0; str[i]!='\0'; i++) {
     if(str[i]>='0' && str[i]<='9') {
        digitCounter++;
     }
     else if(str[i]==' ') {
        spaceCounter++;
     }
  }
  cout << "Digits in String: " << digitCounter << endl;
  cout << "White Spaces in String: " << spaceCounter << endl;
  return 0;
}

Output:

Enter any string: My Roll No is: 1099234
Digits in String: 7
White Spaces in String: 4

Check out this related C++ program:
1. C++ program to count number of vowels and Consonants in a String

Top Related Articles:

  1. C++ Program to Find and display the Transpose of a Matrix
  2. C++ Program to add two numbers
  3. C++ Program to Find largest element in an array
  4. C++ Program to Find Second Smallest Element in an Array
  5. C++ Program to find the Missing Number

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap