atoi strcpy memmove strstr 系列函数实现
面试的时候可能会被问到实现如下函数,必须流畅的写出来,bug Free~
记录一下。
函数原型
#include <stdlib.h>
int atoi(char * digital)
#include <string.h>
char *strcpy(char *dest, const char *src);
void *memmove(void *dest, const void *src, size_t n);
char *strstr(const char *haystack, const char *needle);
具体实现:
int myAtoi(string str) {
if (str.empty()) return 0;
int neg = 1, base = 0, i = 0, n = str.size();
while (i < n && str[i] == ' ')
i++;
if ((i < n) && (str[i] == '+' || str[i] == '-') ) {
neg = (str[i] == '-') ? -1 : 1;
i++;
}
for (; (i < n)&&( str[i] >= '0' && str[i] <= '9'); i++) {
if (base > 0x7FFFFFFF / 10 || base == 0x7FFFFFFF / 10 && str[i] > '7') {
return neg==-1 ? 0x80000000 : 0x7fffffff;
}
base = base * 10 + (str[i] - '0');
}
return base * neg;
}
char *strstr(const char *haystack, const char *needle) {
char *cp = (char *) str1;
char *s1, *s2;
if ( !*str2 )
return((char *)str1);
while (*cp) {
s1 = cp;
s2 = (char *) str2;
while ( *s1 && *s2 && !(*s1-*s2) )
s1++, s2++;
if (!*s2) return(cp);
cp++;
}
return(NULL);
}
int strStr(string haystack, string needle) {
if(haystack.empty() || needle.empty()) return 0;
int len = haystack.size();
int len2= needle.size();
int i=0;
while(i < len) {
int j=0;
while(j<len2){
if(haystack[i+j] !=needle[j]) {
break;
}
j++;
}
if(j==len2) {
return i;
}
i++;
}
return -1;
}
char * strcpy(char * dest, const char *scr) {
if(!dest || !scr) return nullptr;
char *ret = dest ;
int i = 0 ;
for( ; src[i] != '\0'; i++)
dest[i] = src[i];
}
dest[i]='\0';
return ret;
}
void *memmove(void *dest, const void *src, size_t n)
{
if(!dest || !scr || n <=0 ) return nullptr;
if(dest > scr ) {
while(n--) {
*(char*)(dest+n-1) = *(char*)(scr+n-1);
}
} else {
while(n-->0) {
*(char*)dest++ = *(char*)scr++;
}
}
}
|