Convert Snake case to Pascal case in C++

Hello friends, today we will be converting the snake case to the pascal case in C++.

The snake case is one of the programming practice of writing compound words or phrases. We separate the elements with an underscore character instead of spaces and the first letter of every element is usually lowercased within the compound. Eg. code_speedy

The pascal case is also one of the programming practice of writing compound words or phrases. The first letter of every element is uppercased including the first element. There is no space or underscore character in the pascal case. Eg. CodeSpeedy

C++ code to convert snake to pascal case

Approach – We will split the sentence or phrase, by iterating over the input string and splitting the input string by using a separator. Further, we will convert the first letter of every element to the upper case, and the remaining letters to the lower case. Finally, we will create a different string and add all the elements to that string. We can optimize the above approach by doing all of it in once.

Code

#include <iostream>
#include <string>

using namespace std;

string pascalCase(string str, char separator = ' ') {
    string output;

    string temp;
    bool upper;
    for (auto i = str.begin(); i != str.end(); ++i) {
        if (*i != separator) {
            if (upper) {
                temp += toupper(*i);
                upper = false;
            }
            else 
                temp += tolower(*i);
        }
        else {
            output += temp;
            temp = "";
            upper = true;
        }
    }
    if (temp.length() > 0)
        output += temp;

    return output;
}

int main() {
    string input;
    cout << "Enter the phrase or words: ";
    getline(cin, input);

    string output = pascalCase(input);
    cout << "The 'pascal case' is: " << output << endl;

    return 0;
}

Output

Example 1:

Enter the phrase or words: code_speedy
The 'pascal case' is: codeSpeedy

Example 2:

Enter the phrase or words: CodeSpeedy Technology Private Limited is an IT company that provides coding solutions along with various IT services like web development and software development. 
The 'pascal case' is: codespeedyTechnologyPrivateLimitedIsAnItCompanyThatProvidesCodingSolutionsAlongWithVariousItServicesLikeWebDevelopmentAndSoftwareDevelopment.

Thus, we successfully converted the snake case to the pascal case.

See also 

 

Leave a Reply

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