1. Brief Introduction

In C language, the conversion between integers and strings has widely used extension functions (non-standard library), and you can also try simple implementations yourself.


2. Integer to String

1. Extension function itoa

itoa (meaning integer to alphanumeric) is a function that converts an integer to a string.

Under Windows environment, in the <stdlib.h> header file:

char* itoa(int value,char*string,int radix);//value: 要转换的整数,string: 转换后的字符串,radix: 转换进制数,如2,8,10,16 进制等。

Function source code:

char* itoa(int num,char* str,int radix) { char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//Index table unsigned unum;//Store the absolute value of the integer to be converted, the integer to be converted may be negative int i=0,j,k;//i is used to indicate the corresponding position in the string. After conversion, i is actually the length of the string; the order after conversion is reversed. When there is a sign, k is used to indicate the starting position for adjusting the order; j is used for swapping during the order adjustment. //Get the absolute value of the integer to be converted if(radix==10&&num<0)//To convert to a decimal number and it is negative { unum=(unsigned)-num;//Assign the absolute value of num to unum str[i++]='-';//Set '-' at the beginning of the string, and increment the index by 1 } else unum=(unsigned)num;//If num is positive, assign directly to unum //Conversion part, note that the result is in reverse order do { str[i++]=index[unum%(unsigned)radix];//Take the last digit of unum, set it to the corresponding position of str, and increment the index by 1 unum/=radix;//Remove the last digit from unum }while(unum);//Exit the loop until unum is 0 str[i]='\0';//Add the '\0' character at the end of the string, C strings end with '\0'. //Reverse the order if(str[0]=='-') k=1;//If it is negative, the sign does not need to be adjusted, start adjusting from after the sign else k=0;//If not negative, all need to be adjusted char temp;//Temporary variable, used when swapping two values for(j=k;j<=(i-1)/2;j++)//Swap symmetrically from head to tail, i is actually the length of the string, the maximum index is length minus 1 { temp=str[j];//Assign the head to the temporary variable str[j]=str[i-1+k-j];//Assign the tail to the head str[i-1+k-j]=temp;//Assign the value of the temporary variable (actually the previous head value) to the tail } return str;//Return the converted string }

Example program:

Example

#include <stdlib.h> #include <stdio.h> int main() { int number1 = 123456; int number2 = -123456; char string[16] = {0}; itoa(number1,string,10); printf("Number: %d, converted string: %s\n",number1,string); itoa(number2,string,10); printf("Number: %d, converted string: %s\n",number2,string); return 0; }

Effect screenshot:


2. Simple implementation by yourself

Implementation code:

Example

#include <stdio.h> char* Int2String(int num,char *str);//Function declaration int main() { int number1 = 123456; int number2 = -123456; char string[16] = {0}; Int2String(number1,string); printf("Number: %d, converted string: %s\n",number1,string); Int2String(number2,string); printf("Number: %d, converted string: %s\n",number2,string); return 0; } char* Int2String(int num,char *str)//Decimal { int i = 0;//Indicate filling str if(num<0)//If num is negative, make num positive { num = -num; str[i++] = '-'; } //Conversion do { str[i++] = num%10+48;//Take the lowest digit of num. The ASCII codes of characters 0~9 are 48~57; in simple terms, number 0 + 48 = 48, the ASCII code corresponds to character '0' num /= 10;//Remove the lowest digit }while(num);//If num is not 0, continue the loop str[i] = '\0'; //Determine the starting position for adjustment int j = 0; if(str[0]=='-')//If there is a minus sign, the minus sign does not need to be adjusted { j = 1;//Start adjusting from the second position ++i;//Because of the minus sign, the symmetry axis of the swap also needs to move back 1 position } //Symmetric swap for(;j<i/2;j++) { //Swap the values at both ends symmetrically. In fact, it saves the intermediate variable to swap a+b: a=a+b; b=a-b; a=a-b; str[j] = str[j] + str[i-1-j]; str[i-1-j] = str[j] - str[i-1-j]; str[j] = str[j] - str[i-1-j]; } return str;//Return the converted value }

Effect screenshot:


3. String to Integer

1. Extension function

atoi (meaning alphanumeric to integer) is a function that converts a string to an integer.

Under Windows environment, in the <stdlib.h> header file.

int atoi(const char *nptr); // String to integer function, nptr: the string to be converted

Function source code

int atoi(const char *nptr) { return (int)atol(nptr); } long atol(const char *nptr) { int c; /*The current character to be converted (convert characters one by one to numbers)*/ long total; /*Current conversion result*/ int sign; /*Flag whether the conversion result has a minus sign*/ /*Skip spaces, spaces are not converted*/ while ( isspace((int)(unsigned char)*nptr) ) ++nptr; c = (int)(unsigned char)*nptr++;//Get a character ready for conversion sign = c; /*Save sign indicator*/ if (c == '-' || c == '+') c = (int)(unsigned char)*nptr++; /*Skip '+' and '-' signs, do not convert*/ total = 0;//Set conversion result to 0 while (isdigit(c)) {//If the character is a digit total = 10 * total + (c - '0'); /*//Convert the character to the corresponding digit according to the ASCII code, and multiply by 10 to accumulate to the result*/ c = (int)(unsigned char)*nptr++; /*//Get the next character*/ } //Return the result with or without a minus sign according to the sign indicator if (sign == '-') return -total; else return total; }

Example program:

Example

#include<stdio.h> #include<stdlib.h> int main() { printf("String\"123456\"Convert to number: %d\n",atoi("123456")); printf("String\"-123456\"Convert to number: %d\n",atoi("-123456")); return 0; }

2. Simple implementation by yourself

Implementation source code:

Example

#include<stdio.h> int String2Int(char *str);//Function declaration int main() { printf("String\"123456\"Convert to number: %d\n",String2Int("123456")); printf("String\"-123456\"Convert to number: %d\n",String2Int("-123456")); return 0; } int String2Int(char *str)//String to number { char flag = '+';//Indicate whether the result has a sign long res = 0; if(*str=='-')//The string has a minus sign { ++str;//Point to the next character flag = '-';//Set the flag to negative } //Convert character by character and accumulate to the result res while(*str>=48 && *str<=57)//Only convert if it is a digit. ASCII codes of digits 0~9: 48~57 { res = 10*res+ *str++-48;//The ASCII code of character '0' is 48, 48-48=0, which just converts to digit 0 } if(flag == '-')//Handle the case of a negative number { res = -res; } return (int)res; }

Screenshot:


4. Using sprintf() function and sscanf() function

Integer to string

Test code:

Example

#include <stdio.h> char* Int2String(int num,char *str);//Function declaration int main() { int number1 = 123456; int number2 = -123456; char string[16] = {0}; Int2String(number1,string); printf("Number: %d, converted string: %s\n",number1,string); Int2String(number2,string); printf("Number: %d, converted string: %s\n",number2,string); return 0; } char* Int2String(int num,char *str) { sprintf(str, "%d", num); return str; }

Running result:

String to integer

Test code:

Example

#include<stdio.h> int String2Int(char *str);//Function declaration int main() { printf("String\"123456\"Convert to number: %d\n",String2Int("123456")); printf("String\"-123456\"Convert to number: %d\n",String2Int("-123456")); return 0; } int String2Int(char *str)//String to number { char flag = '+';//Indicate whether the result has a sign long res = 0; if(*str=='-')//The string has a minus sign { ++str;//Point to the next character flag = '-';//Set the flag to negative } sscanf(str, "%ld", &res); if(flag == '-') { res = -res; } return (int)res; }

Running result:


5. Appendix: ASCII code table (partial)

Author: Genven_Liang

Original article: https://blog.csdn.net/nanfeibuyi/article/details/80811498