#include <stdio.h>
#include <stdlib.h>
//为避免与标准库中的函数发生混淆,我将它们命名为stringNCopy和stringLength
char *stringNCopy(char *dest, const char *src, size_t count)
{
for (size_t i = 0; i < count; ++i)
{
dest[i] = src[i];
if (!src[i])
{
break;
}
}
return dest;
}
size_t stringLength(const char *str)
{
size_t count = 0;
while (*str++)
{
++count;
}
return count;
}
int main()
{
char *dest = malloc(sizeof(char) * 100);
const char *src = "hello world
世界你好";
stringNCopy(dest, src, stringLength(src) + 1);
printf("%s
", dest);
free(dest);
char arr[50];
char *ret = stringNCopy(arr, "programming 程序设计", 10000);
printf("%s
%s
", arr, ret);
ret = stringNCopy(arr, "Programmer", 1);
printf("%s
%s
", arr, ret);
char test[2];
const char *str = "测试 Test";
ret = stringNCopy(test, str, 100); //非法的操作,可通过编译,但是运行之后可能会报错(vc++下编译并运行之后会报错,Windows下gcc编译后运行无报错)
printf("%s
%s
", test, ret);
printf("%u
%u
%u
", stringLength(""), stringLength(" "), stringLength("字符串 String"));
return 0;
}