Interview Question and Answer - Convert a C++ variable name into a java variable name or vice versa

Q  1.  Modify Variable Names

In every programming language variable naming conventions are different
Like
In C++   :  this_is_a variable
In JAVA : thisIsAVariable

You have to convert a C++ variable name into a java variable name or vice versa.
Assume that Java variable name never contains '_' before any alphabet. In other words , if the given variable name contains '_' before any alphabet, treat the given variable name as C++variable name and generate the result as a Java variable name otherwise vice versa.

Example 1 :

input1 : modify_variableName
output : modifyVariableName

C# language Solution :

 public static string ToConvertVariableName(string str)
        {
            string result;
            if(str.Contains('_'))
                result= ToJava(str);
            else
                result = ToCplus(str);

            return result;
        }
        public static string ToCplus(this string str)
        {
            return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
        }
        public static string ToJava(string str)
        {
            StringBuilder sb = new StringBuilder();
            bool to_upper = true;
            bool start_of_word = true;
            foreach (char ch in str)
            {
                if (char.IsUpper(ch))
                    if (!start_of_word) sb.Append("_");

                if (to_upper)
                    sb.Append(ch.ToString().ToUpper());
                else
                    sb.Append(ch.ToString().ToLower());

                start_of_word = char.IsWhiteSpace(ch);
            }
            return sb.ToString();
        }



Call function


            string str = "thisIsAVariable";
            str = ToConvertVariableName(str);

Comments

Popular posts from this blog

Create Angular 6 Application and Deploy on Firebase