一起來了解c語言的str函數(shù)
strlen:
用于求字符串長度,從首字符開始,到'\0'結(jié)束,'\0'不計入總長度。
函數(shù)實現(xiàn):
size_t my_strlen(const char* ptr) { assert(ptr); const char* ptx = ptr; while (*(++ptx)); return (size_t)(ptx - ptr); }
strcmp:
用于比較兩個字符串大小,注意大小并不是指字符串長度,而是從第一個字符開始比較,比較字符的大小。該函數(shù)返回的是一個int值,不同編譯器,返回的值是不一樣。但是正負(fù)是一致的,當(dāng)?shù)谝粋€大于第二個,返回正值,小于則返回負(fù)值,相等返回0。
函數(shù)實現(xiàn):
int my_strcmp(const char* str1,const char* str2) { assert(str1 && str2); while((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++)))); return (int)(*str1 - *str2); }
strcpy:
用于復(fù)制字符串。
函數(shù)實現(xiàn):
char* my_strcpy(char* dest,const char* source) { assert(dest && source); char* result = dest; while (*(dest++) = *(source++)); return result; }
strcat:
用于在目標(biāo)字符串末尾追加一個字符串。
函數(shù)實現(xiàn):
char* my_strcat(char* a, const char* b) { assert(a && b); char* tmp = a; while (*(++a)); while (*(a++) = *(b++)); *a = '\0'; return tmp; }
strstr:
用于在一個字符串內(nèi)尋找另一個字符串。這于KMP算法有關(guān)。
函數(shù)實現(xiàn):
const char* my_strstr(const char* a, const char* b)//a為長字符串 b為短字符串 { char* cp = (char*)a; char* s1; char* s2; if (!*b) return a; while (*cp) { s1 = cp; s2 = (char*)b; while (*s1 && *s2 && !(*s1 - *s2)) { s1++; s2++; } if (!*s2) return cp; cp++; } return NULL; }
atoi:
這個函數(shù)很有意思,它會把字符串的數(shù)字串轉(zhuǎn)化為int值。
函數(shù)實現(xiàn):
int my_atoi(const char* str) { assert(str); int num = 0; int result = 0; const char* tmp = str; while (*str && *str != '.') { num++; str++; } while (num--) { result += (*tmp - '0') * (int)pow(10, num); tmp++; } return result; }
strncpy
,strncmp
,strncat
:
三個函數(shù)都是限制了字符個數(shù),功能是一樣的。
函數(shù)實現(xiàn):
char* my_strncpy(char* dest, const char* sou, size_t num) { assert(dest && sou); char* tmp = dest; while ((num--) && (*(dest++) = *(sou++))); return tmp; } char* my_strncat(char* a, const char* b, int n) { assert(a && b); char* tmp = a; while (*(++a)); while ((n--) && (*(a++) = *(b++))); *a = '\0'; return tmp; } int my_strncmp(const char* str1, const char* str2,int n) { assert(str1 && str2); while ((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++))) && (n--)); return (int)(*str1 - *str2); }
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Qt GUI圖形圖像開發(fā)之QT表格控件QTableView,QTableWidget復(fù)雜表頭(多行表頭) 及凍結(jié)、固定特
這篇文章主要介紹了Qt GUI圖形圖像開發(fā)之QT表格控件QTableView,QTableWidget復(fù)雜表頭(多行表頭) 及凍結(jié)、固定特定的行的詳細(xì)方法與實例,需要的朋友可以參考下2020-03-03關(guān)于C++中構(gòu)造函數(shù)初始化成員列表的總結(jié)
下面小編就為大家?guī)硪黄P(guān)于C++中構(gòu)造函數(shù)初始化成員列表的總結(jié)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12