1.求字符串长度
#include <assert.h>
size_t mystrlen(const char * dest){
assert(dest! = NULL);//断言
size_t len = 0;
while(*dest ++ != '\0'){//循环增加
len ++;
}
return len;
}
2.字符拷贝函数
#include <assert.h>
char *mystrcpy(char* dest,const char *src){
assert(dest != NULL && src != NULL);
char *pdest = dest;//记录首地址
while((*dest++ = *src++)!='\0');//循环拷贝
return pdest;
}
3.按拷贝n个字符函数
#include <assert.h>
char *mystrncpy(char *dest,cosnt char *src,size_t n){
assert(dest != NULL && src != NULL);
char *pdest = dest;
while(n-->0&&(*dest++ = *src++)!='\0');//附加n--
return pdest;
}
4.字符追加函数
#include <assert.h>
char *mystrcat(char *dest,const char *src){
assert(dest != NULL&&src != NULL);
char *pdest = dest;
while(*dest++ != '\0');//将dest循环到最后一个字符
dest --;
while((*dest++ = *src++)!='\0');
*dest = '\0';
return pdest;
}
5.追加n个字符
#include <assert.h>
char *mystcncat(char *dest,const char *src,size_t n){
assert(dest != NULL&&src != NULL);
char *pest = dest;
while(*dest++ != '\0');
dest--;
while(n-->0&&(*dest++ = *src++)!='\0');
*dest = '\0';
return pdest;
}
6.字符比对函数
#include <assert.h>
int mystrcmp(const char *dest,const char *src){
assert(dest != NULL&&src != NULL);
while(*dest!='\0'&&*src!='\0'&&*dest==*src){
dest++;
src++;
}
return *dest-*src;
}
7.比对两个字符串前n个字符
#include <assert.h>
int mystrncmp(const char *dest,const char *src,size_t n){
assert(dest != NULL&&src != NULL);
while(--n>0*dest!='\0'&&*src!='\0'&&*dest==*src){
dest++;
src++;
}
return *dest-*src;
}
8.万能追加函数
#include <assert.h>
void *mymemcpy(void *dest,const void *src,size_t n){
assert(dest != NULL&&src != NULL);
char *pdest = (char *)dest;
char *psrc = (src *)src;//转化为字符串
while(n-->0){
*psrc++ = *pdest++;
}
return dest;
}
9.字符串逆序
void reverge(char *s){
assert(s != NULL);
size_t len = strlen(s);
for(int i=0;i<len/2;i++){
char R = s[i];
s[i] = s[len-i-1];
s[len-1-i] = s;
}
}
10.字符数字转化为整数
int atoi(const char *ptr){
assert(ptr != NULL);
int num = 0;
int flag = 1;
if(*ptr == '-'){
++ptr;
flag = -1;
}else if(*ptr == '+'){
++ptr;
}
while(*ptr != '\0'){
if(*ptr >= '0' && *ptr <= '9'){
num = num * 10 + (*ptr - '0');
}else{
break;
}
++ptr;
}
return flag * num;
}