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

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

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap