C語言之strncat函數

【FROM MSDN && 百科】

原型: char *strncat(char *dest,const char *src,int n);

#include<string.h>

功能:把src所指字符串的前n個字符添加到dest結尾處(覆蓋dest結尾處的'\0')並添加'\0'。


DEMO:實現自己的strncat函數


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#pragma warning(disable:4996)
char *mystrncat(char *dest,const char *src,int n);
int main(void)
{
	char d[20]="Golden Global";
	char *s="View WinIDE Library";
	system("cls");
    mystrncat(d,s,2);
	printf("%s\n",d);
	printf("%d\n",strlen(d));
	getch();
	return 0;
}

char *mystrncat(char *dest,const char *src,int n)
{
     char *strDest=dest;
	 assert((dest!=NULL)&&(src!=NULL));
	 while(*dest !='\0')
	 {
		 dest++;
	 }
	 while(n && ((*dest++ = *src++)!='\0'))
	 {
		 n--;
	 }
	 *dest='\0';
	 return strDest;
}

DEMO:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
	char d[20]="Golden Global";
	char *s="View WinIDE Library";
	system("cls");
	/* 
	s字符串中只有前n個字符被追加到d字符串,複製過來的s字符串的第一個字符覆蓋了
	d字符串結尾的空字符。s字符串中的空字符及其後的任何字符都不會被複制,並且追加
	一個空字符到所得結果後面。返回值是d。
	*/
	strncat(d,s,5);
	printf("%d\n",strlen(d));
	printf("%s\n",d);
	getch();
	return 0;
}


發佈了90 篇原創文章 · 獲贊 68 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章