1、使用庫函數將數字轉化爲字符串
C語言提供了幾個標準庫函數,能夠將任意類型(整型、長整型、浮點型等)的數字任意轉化爲字符串。
(1)itoa(): 整型 轉化爲 字符串
(2)ltoa(): 長整型 轉化爲 字符串
(3)ultoa():無符號長整型 轉化爲 字符串
(4)gcvt(): 浮點型 轉化爲 字符串
(5)ecvt(): 雙精度浮點型 轉化爲 字符串,結果中不包含十進制小數點
(6)fcvt(): 以指定位數爲轉換精度,其他同ecvt()
(7)sprintf():能夠將任意數字類型轉化爲字符串,可是其速度較上面函數慢。
在Centos上man搜了一下,itoa、ltoa和ultoa在Centos6.7中並不存在,也就是說gcc編譯器沒法識別這三個函數。另外幾個都有。
#include <stdlib.h>
char *gcvt(double number, size_t ndigit, char *buf);
char *gcvt(double number, size_t ndigit, char *buf);
char *ecvt(double number, int ndigits, int *decpt, int *sign);
char *fcvt(double number, int ndigits, int *decpt, int *sign);
char *fcvt(double number, int ndigits, int *decpt, int *sign);
int sprintf(char *str, const char *format, ...);
2、使用庫函數將字符串轉換爲數字
和上面相似,C語言也提供了幾個標準庫函數,能夠將字符串轉換爲任意類型的數字。
(1)atof(): 字符串 轉換爲 雙精度浮點型型
(2)atoi(): 字符串 轉換爲 整型
(3)atol(): 字符串 轉換爲 長整型
(4)strtod(): 字符串 轉換爲 雙精度浮點型,並報告不能被轉換的全部剩餘數字。
(5)strtol(): 字符串 轉換爲 長整型,並報告不能被轉換的全部剩餘數字。
(6)strtoul():字符串 轉換爲 無符號長整型,並報告不能被轉換的全部剩餘數字。
#include <stdlib.h>
double atof(const char *nptr);
double atof(const char *nptr);
int atoi(const char *nptr);
long atol(const char *nptr);
long atol(const char *nptr);
double strtod(const char *nptr, char **endptr);
long int strtol(const char *nptr, char **endptr, int base);
unsigned long int strtoul(const char *nptr, char **endptr, int base);
3、不使用庫函數將字符串轉化爲數字
#include <iostream> using namespace std; int strtoint(char *str) { if(str == NULL) //函數入口參數檢查 { return 0; } const char *pstr = str; int temp; //臨時存放轉換後的數據 if(str[0] == '+' || str[0] == '-') //第一位爲+/-時,先看後面的 { str++; } while(*str) //遍歷字符串,若是字符在0~9,則轉化 { if(*str < '0' && *str > '9') { break; } temp = temp*10 + *str - 48; str++; } if(pstr[0] == '-') //若是以‘-’開頭,取反 { temp = -temp; } return temp; } int main() { char str[20]; cin.getline(str, 20); cout<<strtoint(str)<<endl; return 0; }
4、編程實現strcpy函數
strcpy函數原型:
char *strcpy(char *dest, const char *src);
#include <stdio.h> void my_cpy(char* str1, char* str2) { if(str1 == NULL || str2 == NULL) //函數入口參數檢查 { return; } while((*str1++ = *str2++) != '\0'); //將str2的全部內容複製到str1中 return; } int main() { char str1[] = "hello"; char str2[] = "world"; my_cpy(str1, str2); printf("%s\n%s\n", str1, str2); return 0; }
5、編程實現memcpy函數
內存複製的實現
#include <stdio.h> #include <assert.h> void my_memcpy(char* memto, const char* memfrom, size_t size) { assert((memto != NULL) && (memfrom != NULL)); //入口參數檢查 char *tempfrom = memfrom; char *tempto = memto; while(size-- > 0) { *tempto++ = *tempfrom++; } } int main() { char str1[] = "hello world"; char str2[20] = ""; my_memcpy(str2, str1, 4); str2[4] = '\0'; printf("%s\n", str2); return 0; }
memcpy函數有選擇性的複製字符串中的字符。程序中複製了str1的前四個字符。
6、strcpy與memcpy的區別
區別:
(1)複製的內容不一樣。strcpy只能複製字符串,memcpy能夠複製任意內容,如字符串、整型、結構體和類等。
(2)複製的方法不一樣。strcpy不須要指定長度,它是遇到‘\0’結束的,memcpy是有其第三個參數決定。
(3)用途不一樣。一般在複製字符串時用strcpy,其餘數據類型用memcpy。