Q5. Code a function, named CountNumerics, that accepts a parameter of a string , named str1, and returns the number of numeric characters (‘0’ .. ‘9’) + in the string. Helpful clues: The string class has a function called length() that can be accessed by str1.length(). To access an individual character in the string; use string indexing (str1[i]) where I is an integer. Indexing of a string array starts at 0.
Program
#include <iostream>
#include <string>
using namespace std;
//function count and return the number of numeric characters in
str1
int CountNumerics(string str1)
{
int count = 0;
for(int i=0; i<str1.length(); i++)
{
if(str1[i]>='0' && str1[i]<='9')
count++;
}
return count;
}
//main function
int main()
{
//testing
string str1 = "abcd12345";
cout<<"The number of numeric characters: "<<
CountNumerics(str1)<<endl;
return 0;
}
Output:
The number of numeric characters: 5
Solving your question and
helping you to well understand it is my focus. So if you face any
difficulties regarding this please let me know through the
comments. I will try my best to assist you.
Thank you.
Get Answers For Free
Most questions answered within 1 hours.