自己實現一個字串拼接函式
阿新 • • 發佈:2019-01-08
今天去面試了一家公司,其中有一個程式設計題:實現字串拼接函式,要求不呼叫庫函式。說來慚愧,自己審題不嚴,理解成了字串複製函式。粗心是我的另一大缺點,現在我在努力改進,雖然面試的不太好,但是這個函式我還是要實現一遍。
程式碼如下:
#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;
}
今天的程式碼就是這個啦~給自己鼓個掌!