可见使用位移不但效率高,而且代码书写简洁至极,推荐使用!
#include
char *My_strncpy(char *strDes, const char *strSrc, int n)
{
char *sS = strSrc;
char *sD = strDes;
int srclen = strlen(strSrc);
//为了避免越界计算最终要拷贝多少个字符
n = srclen > n ? n : srclen;
//方法一,采用下标
/*int constN = n;
int indexN = n;
while (indexN >= 0)
{
if (constN == indexN)
{
*(sD + (constN - 0)) = '\0';
}
else
{
*(sD + (indexN)) = *(sS + indexN);
printf("%c\n", *(sD + (indexN)));
}
indexN--;
}*/
//方法二,采用位移 (推荐使用)
while (n > 0)
{
*sD = *sS;
sS++;
sD++;
n--;
}
//将末尾补\0标志字符串结束
*sD = '\0';
//这里返回值的作用是为了可以进行级联操作
//比如: strcat(str, strncpy(buf, src, 10));
return strDes;
}
int main(void)
{
char strD[100];
char strS[] = "helloworld";
My_strncpy(strD, strS, 5);
printf("%s", strD);
system("pause");
return 0;
}