標(biāo)題: strncpy函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用 [打印本頁(yè)]

作者: xiaojuan    時(shí)間: 2014-9-24 22:30
標(biāo)題: strncpy函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用
//:Vc++6.0  String  strncpy函數(shù)
//功能:指定大小的字符串拷貝
//參數(shù):dest 目標(biāo)字符串  str 要考的字符串  num 拷貝大小
//返回值:dest字符串地址
#include<stdio.h>

char *strncpy(char *dest, const char *str, int num);

int main()
{
char str1[]= "To be or not to be";
char str2[6];
strncpy (str2,str1,5);
printf("str2 = %s\n", str2);

return 0;
}

char *strncpy(char * dest, const char *str, int num)
{
//查錯(cuò)
    if (dest == NULL || str == NULL)
    {
perror("dest or str");
return NULL;
    }
//求長(zhǎng)度
char *temp1 = dest;
const char *temp2 = str;
    int len;
while (*(temp2++) != '\0');
len = temp2 - str;

//拷貝
    if (num <= 0)
        *temp1 = '\0';
    else  if (num >= len)
    {
        while (*str != '\0')
            *(temp1++) = *(str++);
        *temp1 = '\0';
    }
    else
    {
int i;
        for (i = 0; i < num; i++)
        {
            *(temp1++) = *(str++);
        }
        *temp1 = '\0';
    }
return dest;
}
//在vc++6.0中的運(yùn)行結(jié)果為:str2 = To be
//注:在拷貝時(shí)已經(jīng)在尾部加了'\0'//:~






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1