Friday, March 2, 2012

String To Integer and Integer to String Conversion in C

In modern languages like Java, C# etc., there is a provision of function to handle String to Integer and Integer to String conversion. But in case of C, you should explicitly convert.
String to Integer Conversion
String is a array of characters. So changing each character successively into integer  changes whole string into integer. To change a character into an integer, here is a simple idea. The idea is, subtract the zero character from the character you want to change. For example to change  character 1 into integer 1 subtract character 0 from character one i.e. ‘1’ - ‘0’ results integer 1. A portion of a C code is given below:

int Convert(char input[]) {
    int sum = 0, i, p = 1, digit;
    for(i = strlen(input) - 1; i>=0; i--) {
        digit = input[i] - '0';
        sum += digit*p;
        p *= 10;
    }
    return sum;
}


Integer to String Conversion

Integer to string conversion is reverse of string to integer conversion described above. In this process, each digit is extracted from the integer and character ‘0’ is added to make it char. At last all the digits that are converted to char are combines to make string. A portion of C code is
void IntToString(int n) {
    int k = 0;
    if(n == 0) {
        return 0;
    }
    k = IntToString(n/10);
    string[k] = n%10 +'0';
}

You must add a end of line ‘\0’ character at the end of the converted string.

1 comment:

  1. your function must have an integer return type. and only the first character is updated every time. please check...

    ReplyDelete