Guidelines for using the strcat function

  • 2020-04-02 03:20:16
  • OfStack

The prototype             Extern char *strcat(char *dest,char * SRC);
usage             # include < String. H >

function             Add the SRC reference string to the end of dest (overwriting the '\0' at the end of dest) and add '\0'. Returns a pointer to dest.

instructions                 The memory area indicated by SRC and dest must not overlap and dest must have enough space to hold the SRC string.

For example,


 char str4[] = "Hello world";
 char str5[] = "Hello World";
 cout << strcat(str4,str5) << endl;

It's going to go wrong because str4 doesn't have enough space

The following is an implementation of my own, shortcomings, also hope to correct!!


#include "stdafx.h"
#include <iostream>
#include <assert.h>

using namespace std;
//Concatenation string
char* mystrcat(char* destStr,const char* srcStr)   //What if two strings are the same string?
{
  assert(destStr != NULL && srcStr != NULL);

  char* temp=destStr;

  while(*destStr != '0')
  {
    ++destStr;
  }
  while(*destStr++ = *srcStr++)
    NULL;
  return temp; //To implement the chain operation, the destination address is returned
}
int _tmain(int argc, _TCHAR* argv[])
{
  char str1[25] = "Hello world";
  char str2[] = "Hello World";
  cout << mystrcat(str1,str2) << endl;
  return 0;
}


Let's look at the source function again:


//=======================================================
#include "string.h"
char * __cdecl strcat ( char * dst, const char * src )
{
  char * cp = dst;     //Save the DST pointer
  while( *cp )
    cp++;         //Find the end of the DST string
  while( *cp++ = *src++ ) ; //Copy the SRC string after the DST
  return( dst );      //Returns a pointer to the DST string
}
//=============================================

For example:


//=================================================
strcat() Accepts two string arguments. Adds a copy of the second string to the end of the first string, making the first string a new composite string and the second string unchanged. 
#include<stdio.h>
#include<string.h>
int main(void)
{
  char str1[20];
  char str2[]="Hello word";
  
  gets(str1);   //Must be initialized
  strcat(str1,str2);
  puts(str2);
  puts(str1);
  
  getchar();
  return 0;
}

The above program copies the string2 string to the end of string1. The first string becomes a new composite string

Note: string1 must be initialized before the strcat() function calls string1.


Related articles: