In this HackerEarth Case conversion problem solution, You are given a string S 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:
  1. ComputerHope
  2. FedEx
  3. WordPerfect
Note: In the camel case string, the first character may or may not be capitalized.


HackerEarth Case conversion problem solution


HackerEarth Case conversion problem solution.

def case_conversion():
    t = int(raw_input())
    for _ in xrange(t):
        s = raw_input()
        res = []
        res.append(s[0].lower())
        for i in s[1:]:
            if i.isupper():
                res.append('_')
                res.append(i.lower())
            else:
                res.append(i)
        print ''.join(res)

case_conversion()


Second solution

#include<bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin>>t;
    assert(t>=1 && t<=100);
    while(t--) {
        string s; cin>>s;
        int n=s.size();
        assert(n>=1 && n<=100);
        for(char c:s) {
            assert(islower(c) || isupper(c));
        }
        for(int i=0;i<n;i++) {
            if(isupper(s[i])) {
                if(i>0) cout<<'_';
                char c=s[i];
                putchar(tolower(c));
            }
            else cout<<s[i];
        }
        cout<<endl;
    }
    
    return 0;
}