Check if usage of capitals is correct in a word in C++

In this article, let’s learn how to check if the usage of capitals is correct in the given word with the help of C++ programming. We can say capitals are used correctly when all characters of a word are in uppercase i.e., “EXAMPLE” or all characters are in lowercase i.e., “example” or if the first letter of the world is capitalized i.e., “Example“.

Check if the usage of capitals is correct in a word in C++

Here is the code to check if capitals are used correctly in a word or not.

#include <iostream>
using namespace std;

class Solution {
public:
    bool verifyCapitalsWord(string word) {
        int caps = 0;
        int smalls = 0;
        for(auto ch : word){
            if(ch >= 'a' && ch<='z'){
                smalls++;
            }else if(ch >='A' && ch<='Z'){
                caps++;
            }
        }
       if(caps == 0) return true;
       if(smalls ==0) return true;
       if(caps ==1 && (word[0] >= 'A' && word[0] <= 'Z')) return true;
        return false;
    }
};

int main(){
    string w = "Mumbai";
    Solution s;
    bool ans = s.verifyCapitalsWord(w);
    ans ? "The given word is capitalized correctly":"The given word is not capitalized correctly";
}

Output:

The given word is capitalized correctly

In the above code, first, I am importing iostream head files using the syntax #include. Then I used the syntax using namespace to define that I am using the std (standard) namespace. Then I defined a class with a public method called verifyCapitalWord(string word) that accepts a string as an argument and returns a boolean value. Let’s discuss the implementation of the function at last. After this, I have defined the main() function. In the main() function, I have defined a string w, initialized object s of class Solution, invoked the function verifyCapitalWorld(string word) with string w, and stored it as a boolean variable ans. Finally, I displayed the output based on ans being true or false.

Now let’s discuss the verifyCapitalWord(string word function) function. First, I declared 2 variables, caps, and smalls, to zero. Now I iterated through each character in the word and counted the number of capital and small letters. These values are stored in caps and smalls variables.  If caps == 0, then all letters must be in lowercase, and if smalls == 0, then all letters must be in uppercase. We know either of these cases leads to true, so I returned true. In the last if statement, I am checking if the first letter of the word is the only capital or not. If none of the conditions get satisfied, then I am returning false.

Leave a Reply

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