Today we simulate the implementation of the two functions strcat and strncat.
First, let's take a look at the strcat function, which means connecting the second string to the end of the first string. Let's take a look at the function prototype: Char *strcat (char *dest, char *src) adds the string src refers to at the end of the dest (overwriting the ' + ' at the end of the dest) and adding '% '. Here's a look at the program:
#include <stdio.h> #include <assert.h>char *my_ strcat (CHAR&NBSP;*DEST,&NBSP;CHAR&NBSP;*SRC) {Char *ret = dest;assert (dest); assert (SRC); while (*dest) //finds the end of the first string through a while loop {dest++;} while (*dest++ = *src++) //connects the second string to the first string through this while loop {;} Return ret;} Int main () {char dest[20] = "Hello";char *psrc = "world"; char *ret = my_strcat (DEST,PSRC);p rintf ("%s\n", ret); return 0;}
Let's introduce the function of strncat, in fact it is roughly the same as strcat, but it's the difference between "n". Let's look at the function prototype: char *strncat (Char *dest, char *src, int n), This function is add the first n characters of the string that SRC refers to at the end of the dest (overwrite the ' + ' at the end of the dest) and add '/s '. The difference between this function and the previous one is that the function has a requirement for the number of characters in the second string. So let's take a look at the code:
#include <stdio.h> #include <assert.h>void *my_strncat (char *dest, const char *src,int N) {assert (dest); ASSERT (SRC); while (*dest! = ') {dest++;} while (n--)//through this while loop, the second string of the first n of the Word connect prompt to the first string {*dest++ = *src++;} *dest = ' + ';} int main () {char arr1[10] = "abc"; char arr2[] = "DEFGH"; int num = 0;scanf ("%d", &num); My_strncat (Arr1,arr2,num);p UTS ( ARR1); return 0;}
Through these two pieces of code, I believe that you have been able to understand the difference between the two functions of strcat and Strncat.
This article is from the "10944002" blog, please be sure to keep this source http://chrisapril.blog.51cto.com/10944002/1766313
Simulation for strcat and Strncat