C++ How To Count Digits in a String
Count Digits in a String
Use the isdigit() function to count how many digits a string has:
Example
string text = "W3Schools 2026";
int count = 0;
for (char c : text) {
if (isdigit(c)) {
count++;
}
}
cout << "Number of digits: " << count;
Explanation:isdigit() (from the <cctype> library) returns true if the character is a digit from 0 to 9.
"W3Schools 2026" has 5 digits: 3, 2, 0, 2 and 6.