C++

Find The Amount Of Digits And White Spaces In A String Using A C++ Program

This software counts the amount of digits and white spaces in an input string that the user has entered.

Program that count the number of digits and white spaces in a String, for instance

The input string is stored in a string object in this program. If you want, you can substitute a char array for a string object because it has a defined size. As a result, if the user enters a string that is larger than the char array’s size of 100, the computer will truncate it.

Here, we are using a for loop to iterate through the string from the first character to the last character (‘0’), counting the numerals and white spaces as we go. You must study the C++ programming concepts of the for loop and strings in order to comprehend this program.

#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

Related Articles

Leave a Reply

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

Back to top button