Convert Camel Case String to Snake Case in C++
Last Updated :
05 Mar, 2023
Programming can be complicated, and it’s essential to ensure that our code is readable and well-structured. One way to improve code clarity is by using meaningful and descriptive variable and function names. To make every element name unique and more meaningful we use camel case and snake case are two widely used conventions for naming variables and functions. Let us check both of them
Snake Case
Snake case strings begin with lowercase and separate words with underscores where each word start with lowercase.
Example:
event_listener
Camel Case
Camel case strings begin with lowercase and capitalize the first letter of subsequent words
Example:
EventListener
Conversion from Camel Case to Snake case
In C++, we can easily convert camel case strings to snake case strings by replacing capital letters with underscores and the lowercase letters that follow them. In this article, we’ll delve into how to perform this conversion in C++.
Example:
Camel Case: GeeksForGeeks
Snake Case: geeks_for_geeks
Program to implement conversion
Given a string in camel case, the task is to write a C++ program to convert the given string from camel case to snake case and print the modified string.
Example
Input: GeeksForGeeks
Output: geeks_for_geeks
Approach of conversion
The approach to the topic is simple and easy to understand. The approach is mentioned below:
- First, we initialize a variable ‘result’ with an empty string and append the first character (in lower case) to it.
- Now iterate over each character of the string from the first index to the last index, if the character is in the upper case alphabet, we append ‘_’ and the character (in lower case) to the result, otherwise just append the character only.
Time Complexity of the Program
Time Complexity: O(n)
Auxiliary Space: O(n)
Implementation of the above topic:
C++
#include <iostream>
#include <string>
using namespace std;
string camelToSnake(string str)
{
string result = "" ;
char c = tolower (str[0]);
result+=( char (c));
for ( int i = 1; i < str.length(); i++) {
char ch = str[i];
if ( isupper (ch)) {
result = result + '_' ;
result+= char ( tolower (ch));
}
else {
result = result + ch;
}
}
return result;
}
int main()
{
string str = "GeeksForGeeks" ;
cout << camelToSnake(str);
return 0;
}
|
Output
geeks_for_geeks
Share your thoughts in the comments
Please Login to comment...