Given a string in Snake Case, the task is to write a Java program to convert the given string from snake case to camel case and print the modified string.
Examples:
Input: str = “geeks_for_geeks” Output: GeeksForGeeks Input: str = “snake_case_to_camel_case” Output: SnakeCaseToCamelCase
Method 1: Using Traversal
- The idea is to first capitalize the first letter of the string.
- Then convert the string to string builder.
- Then traverse the string character by character from the first index to the last index and check if the character is underscored then delete the character and capitalize the next character of the underscore.
- Print the modified string.
Below is the implementation of the above approach:
Java
import java.io.*;
class GFG {
public static String
snakeToCamel(String str)
{
str = str.substring( 0 , 1 ).toUpperCase()
+ str.substring( 1 );
StringBuilder builder
= new StringBuilder(str);
for ( int i = 0 ; i < builder.length(); i++) {
if (builder.charAt(i) == '_' ) {
builder.deleteCharAt(i);
builder.replace(
i, i + 1 ,
String.valueOf(
Character.toUpperCase(
builder.charAt(i))));
}
}
return builder.toString();
}
public static void
main(String[] args)
{
String str = "geeks_for_geeks" ;
str = snakeToCamel(str);
System.out.println(str);
}
}
|
Time Complexity: O(n) where n is the length of the string
Auxiliary Space: O(1)
Method 2: Using String.replaceFirst() method
- The idea is to use String.replaceFirst() method to convert the given string from snake case to camel case.
- First, capitalize the first letter of the string.
- Run a loop till the string contains underscore (_).
- Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore.
- Print the modified string.
Below is the implementation of the above approach:
Java
class GFG {
public static String
snakeToCamel(String str)
{
str = str.substring( 0 , 1 ).toUpperCase()
+ str.substring( 1 );
while (str.contains( "_" )) {
str = str
.replaceFirst(
"_[a-z]" ,
String.valueOf(
Character.toUpperCase(
str.charAt(
str.indexOf( "_" ) + 1 ))));
}
return str;
}
public static void
main(String args[])
{
String str = "geeks_for_geeks" ;
System.out.print(snakeToCamel(str));
}
}
|
Time Complexity: O(n) where n is the length of the string
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!