main()函数中的例子全部取于cplusplus网站
模拟实现strncat
char* Strncat(char* dest,const char* src,size_t num){
assert(dest != NULL);
assert(src != NULL);
unsigned int i = 0;
for(i = 0;i < num; i++);
strncpy(&dest[i],src,num);
return dest;
}
int main(){
char str1[20];
char str2[20];
strcpy (str1,"To be ");
strcpy (str2,"or not to be");
Strncat (str1, str2, 6);
puts (str1);
return 0;
}
模拟实现strncmp
int Strncmp(const char *dest, const char*src, int count)
{
assert(dest != NULL);
assert(src != NULL);
while (count && *dest != '\0' && *src != '\0')
{
if (*dest > *src){
return 1;
}
else if (*dest < *src){
return -1;
}
else{
dest++;
src++;
count--;
}
}
}
int main()
{
char str[][5] = { "R2D2", "C3PO", "R2A6" };
int n;
printf("Looking for R2 astromech droids...\n");
for (n = 0; n<3; n++)
if (Strncmp(str[n], "R2xx", 2) == 0)
{
printf("found %s\n", str[n]);
}
strncpy模拟实现
char* Strncpy(char* dest, const char* src, size_t num){
assert(dest != NULL);
assert(src != NULL);
int64_t i = 0;
for(i = 0;(unsigned)i < num;i++){
dest[i] = src[i];
}
dest[num] = '\0';
return dest;
}
int main(){
char str1[]= "To be or not to be";
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
Strncpy ( str2, str1, sizeof(str2) );
/* partial copy (only 5 chars): */
Strncpy ( str3, str2, 7 );
str3[7] = '\0'; /* null character manually added */
puts (str1);
puts (str2);
puts (str3);
return 0;
}