Tuesday, January 11, 2011

CONVERTING STRING TO INT32 WITHOUT USING BUILTIN FUNCTION

Hi all I am writing this post for those people who keep on giving interviews. Most of the time interviewr ask questing which you were not expecting. One of those question is "How to convert string to integer with out using built-in function?". If you you are a developer you have never thought of converting string to integer with out out using built-in function, because there are functions are available, However; interviewer ask these type of question.


Any ways following is the code to convert string to integer with out using built-in function.

        Int32 ConvertToInt(String str)
        {
            try
            {
                int result = 0;

                for (int i = 0; i < str.Length; i++)
                {
                    switch (str[i])
                    {
                        case '0':
                            result = result * 10 + 0;
                            break;
                        case '1':
                            result = result * 10 + 1;
                            break;
                        case '2':
                            result = result * 10 + 2;
                            break;
                        case '3':
                            result = result * 10 + 3;
                            break;
                        case '4':
                            result = result * 10 + 4;
                            break;
                        case '5':
                            result = result * 10 + 5;
                            break;
                        case '6':
                            result = result * 10 + 6;
                            break;
                        case '7':
                            result = result * 10 + 7;
                            break;
                        case '8':
                            result = result * 10 + 8;
                            break;
                        case '9':
                            result = result * 10 + 9;
                            break;
                        default:
                            throw new FormatException();
                    }
                }

                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }

No comments:

Post a Comment