Case conversion

You are given a string in the camel case format. Your task is to convert this string into the snake case format.

Examples of the camel case strings are as follows:

  • ComputerHope
  • FedEx
  • WordPerfect

Note: In the camel case string, the first character may or may not be capitalized.

Examples of the snake case strings are as follows:

  • computer_hope
  • fed_ex
  • word_perfect

Example:

Input:  s = "primeCheck"
Output: prime_check

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string caseConversion(string s)
{
    int n = s.size();
    string ans = "";
    for (int i = 0i < ni++)
    {
        if (s[i] >= 'A' && s[i] <= 'Z')
        {
            if (i == 0)
                ans += s[i] + 32;
            else
            {
                ans += '_';
                ans += s[i] + 32;
            }
        }
        else
            ans += s[i];
    }
    return ans;
}
int main()
{
    string s = "primeCheck";

    cout << caseConversion(s<< "\n";

    return 0;
}


No comments:

Post a Comment