1.面试常问道的 字符串拷贝函数的编写
</pre><pre name="code" class="cpp">/********************************************
*实现字符串的拷贝工作
*返回值用来实现链式操作
*如 strlen(strcpy(str, "fsdfsdf"));
********************************************/
char *strcpy(char *dest, const char *sour){
if(dest == NULL || sour == NULL)
return NULL;
char *cp = dest;
while(( *cp++ = *sour++ ) != 0);
return dest;
}
2.数值型转换为字符串 也就是 itoa的实现
/*整形数值转变为字符数组的atoi 返回值char* 也是为了实现链接操作*/
char* itoa(const int number, char *dest, int mod){
if(dest == NULL || mod <= 0)/*异常检测*/
return NULL;
char tmp [100];
int i = 0, j = 0, num = number;
if (num < 0){/*负数型字符串处理*/
dest[j++] = '-';
num = -1 * num;
}
while(num){/*核心*/
tmp[i++] = '0' + num % mod;
num/=mod;
}
tmp[i] = 0;
i--;
while(i >= 0)/*逆置*/
dest[j++] = tmp[i--];
dest[j] = 0;
return dest;
}
3.字符串转换为整型数 也就是 atoi的实现
<pre name="code" class="cpp">/*字符串转变为整型数atoi*/
int atoi(const char *str){
int ret = 0;
int i = 0;
int symbol = 1; /*符号标志*/
if(str[i++] == '-')
symbol = -1;
while(str[i] != 0){ /*转换实现*/
if(str[i] >'9' || str[i] <'0'){
return 0;
}
ret = (str[i] - '0') + ret * 10;
i++;
}
return ret * symbol;
}