How to convert snake case format containing underscore to java variable format and vice versa?
Usually c variable contains underscore between words but java contains firstletter is lowercase and other first letter in upper case.
This is very famous test program usually asked in online test.
example :
input = bb_cann_fb_hnh
output = bbCannFbHnh
and vice versa.
Usually c variable contains underscore between words but java contains firstletter is lowercase and other first letter in upper case.
This is very famous test program usually asked in online test.
example :
input = bb_cann_fb_hnh
output = bbCannFbHnh
and vice versa.
public class VariableFormatter {
public static void main( String[] args )
{
System.out.println(modifyVariableString("bb_cann_fb_hnh"));
System.out.println(modifyVariableString("bbCannFb"));
}
private static String modifyVariableString(String s) {
String output;
//check if it is c variable
if(s.contains("_")){
output= javaFormatter(s);
}else{
output= cFormatter(s);
}
return output;
}
private static String cFormatter(String string) {
string= string.replaceAll("([A-Z])", "_$1").toLowerCase();
return string;
}
static String javaFormatter(String s){
String[] elements= s.split("_");
StringBuilder sb = new StringBuilder(elements[0]);
for(int i=1;i<elements.length;i++){
elements[i]=elements[i].substring(0, 1).toUpperCase()+elements[i].substring(1);
sb.append(elements[i]);
}
String output=sb.toString();
return output;
}
}
public static void main( String[] args )
{
System.out.println(modifyVariableString("bb_cann_fb_hnh"));
System.out.println(modifyVariableString("bbCannFb"));
}
private static String modifyVariableString(String s) {
String output;
//check if it is c variable
if(s.contains("_")){
output= javaFormatter(s);
}else{
output= cFormatter(s);
}
return output;
}
private static String cFormatter(String string) {
string= string.replaceAll("([A-Z])", "_$1").toLowerCase();
return string;
}
static String javaFormatter(String s){
String[] elements= s.split("_");
StringBuilder sb = new StringBuilder(elements[0]);
for(int i=1;i<elements.length;i++){
elements[i]=elements[i].substring(0, 1).toUpperCase()+elements[i].substring(1);
sb.append(elements[i]);
}
String output=sb.toString();
return output;
}
}
Comments
Post a Comment