找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3320|回復(fù): 0
打印 上一主題 下一主題
收起左側(cè)

strncpy函數(shù)實現(xiàn)及簡單應(yīng)用

[復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
ID:51090 發(fā)表于 2014-9-24 22:30 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
//: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)
{
//查錯
    if (dest == NULL || str == NULL)
    {
perror("dest or str");
return NULL;
    }
//求長度
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中的運行結(jié)果為:str2 = To be
//注:在拷貝時已經(jīng)在尾部加了'\0'//:~

分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 分享淘帖 頂 踩
回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機(jī)版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表