Java program to convert camel case string to snake case

In the case of the camel, the task is to write a Java program that converts the given string from the camel into a queue and outputs 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 the variable 'result' with an empty string and add the first character (in lowercase).
  • Now iterate over each character in the string from the first index to the last index. If a character is a capital letter we add '_' and character (in lower case) as result, otherwise we just add character.

Below is the implementation of the above approach:

 

 
class GFG {

	// Function to convert camel case
	// string to snake case string
	public static String camelToSnake(String str)
	{

		// Empty String
		String result = "";

		// Append first character(in lower case)
		// to result string
		char c = str.charAt(0);
		result = result + Character.toLowerCase(c);

		// Tarverse the string from
		// ist index to last index
		for (int i = 1; i < str.length(); i++) {

			char ch = str.charAt(i);

			// Check if the character is upper case
			// then append '_' and such character
			// (in lower case) to result string
			if (Character.isUpperCase(ch)) {
				result = result + '_';
				result
					= result
					+ Character.toLowerCase(ch);
			}

			// If the character is lower case then
			// add such character into result string
			else {
				result = result + ch;
			}
		}

		// return the result
		return result;
	}

	public static void main(String args[])
	{
		// Given string str
		String str = "GeeksForGeeks";

		// Print the modified string
		System.out.print(camelToSnake(str));
	}
}

Output: 

geeks_for_geeks

Method 2: Using String.replaceAll method 

  • The idea is to use the String.replaceAll method to change a specific camel chain in the case of a snake.
  • The String.replaceAll method takes two parameters - a regular expression and a replacement string. This replaces the regular expression with a replacement string and returns the changed string.

Below is the implementation of the above approach: 

 

 
class GFG {

	// Function to convert camel case
	// string to snake case string
	public static String
	camelToSnake(String str)
	{
		// Regular Expression
		String regex = "([a-z])([A-Z]+)";

		// Replacement string
		String replacement = "$1_$2";

		// Replace the given regex
		// with replacement string
		// and convert it to lower case.
		str = str
				.replaceAll(
					regex, replacement)
				.toLowerCase();

		// return string
		return str;
	}

	// Driver Code
	public static void main(String args[])
	{
		// Given string str
		String str = "GeeksForGeeks";

		// Print the modified string
		System.out.print(camelToSnake(str));
	}
}

Output: 

geeks_for_geeks

 

Submit Your Programming Assignment Details