Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string.
Examples:
Input: GeeksForGeeks
Output: geeks_for_geeks
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case
Method 1: Naive Approach
- 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 first index to the last index, if the character is upper case alphabet, we append ‘_’ and the character (in lower case) to result, otherwise just append the character only.
Below is the implementation of the above approach:
Java
class GFG {
public static String camelToSnake(String str)
{
String result = "";
char c = str.charAt(0);
result = result + Character.toLowerCase(c);
for (int i = 1; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
result = result + '_';
result
= result
+ Character.toLowerCase(ch);
}
else {
result = result + ch;
}
}
return result;
}
public static void main(String args[])
{
String str = "GeeksForGeeks";
System.out.print(camelToSnake(str));
}
}
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using String.replaceAll method
- The idea is to use the String.replaceAll method to convert given string from camel case to snake case.
- The String.replaceAll method accepts two parameters a regular expression and a replacement string. It replaces the regular expression with the replacement string and prints the modified string.
Below is the implementation of the above approach:
Java
import java.util.regex.*;
class GFG {
public static String
camelToSnake(String str)
{
String regex = "([a-z])([A-Z]+)";
String replacement = "$1_$2";
str = str
.replaceAll(
regex, replacement)
.toLowerCase();
return str;
}
public static void main(String args[])
{
String str = "GeeksForGeeks";
System.out.print(camelToSnake(str));
}
}
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
13 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...