今天去面试了一家公司,其中有一个编程题:实现字符串拼接函数,要求不调用库函数。说来惭愧,自己审题不严,理解成了字符串复制函数。粗心是我的另一大缺点,现在我在努力改进,虽然面试的不太好,但是这个函数我还是要实现一遍。
代码如下:
#include <stdio.h>
typedef unsigned int ui_t;//为unsigned int类型重命名
//字符串拼接函数
ui_t strlcatCode(char *deststr ,const char * srcstr,ui_t size)
{
ui_t d_i = 0;
ui_t s_i = 0;
while(deststr[d_i] != 0)
d_i ++;//找到目标字符串的结束位置
//此处d_i<size - 1的原因为了防止越界,字符串的结尾要为‘\0’,占用一个字符
while(srcstr[s_i] != '\0' && d_i < size - 1)
{
deststr[d_i] = srcstr[s_i];
d_i ++;
s_i ++;
}
deststr[d_i] = '\0';
return d_i;
}
int main()
{
ui_t len = 0;
char ch[8] = "asd";
len = strlcatCode(ch,"123456",8);
printf("%s,%u\n",ch,len);
return 0;
}
今天的代码就是这个啦~给自己鼓个掌!