C String Concatenation

Concatenation is the process to append second string to the end of first string. In this article we are going to discuss how to concatenate strings in C by using different methods.

The standard C library function which is used to concatenate string is strcat().

Function Prototype:

$ char *strcat(str1,str2);

where str1 is first stringand str2 is second string. Return value of the function is the pointer to the concatenated string.

Now, with the help of example we will see how concatenation is performed.

Example1:

$ strcat(str1,str2);
 where str1 is “Bella”
    str2 is “Whitmann”
       
after concatenation of string, first string will be
       
           str1   “Bella Whitmann”
           str2   “Whitmann”

while string2 will remain same.

Example2:

$ strcat(str2,str1);
where str1 is “Bella”
         str2 is “Whitmann”
           
  after concatenation of string, concatenated string will be
       
         str1  “Bella”
                 str2  “Bella Whitmann”

while string1 will remain same.

Declaration in C Header File

String handling functions are declared under <string.h>headerfile. If one wants to use standard function to concatenate, this header file needs to be included.

Hence, we can achieve string concatenation in two ways. One is with using the Standard C library function and other is without using C library function. Following are example programs to demonstrate both the ways. String concatenation without using C library function can be implemented in multiple ways.

We will discuss that as well in coming sections with example.

Concatenation of Two Strings by Using C Library Function

#include<stdio.h>

#include<string.h>

#define BUF_SIZE 256
 int main()
 {
    char S1[BUF_SIZE],S2[BUF_SIZE];  /* Two string buffers */

    printf("Enter the first string\n"); ] /* Print message to the console for user to input 1st string*/
    fgets(S1,BUF_SIZE,stdin);           /* store the user input string in S1 buffer */
    S1[strlen(S1)-1] = '\0';

    printf("Enter the second string\n");/* Print message to user to input 2nd string*/
    fgets(S2,BUF_SIZE,stdin);           /* store the user input string in S2 buffer */
    S2[strlen(S2)-1] = '\0';

    strcat(S1,S2);   /*Call the standard function with S1 and S2 strings */

    printf("\n Concatenated string is %s\n\n",S1); /*Output : S1 gets appended with S2 */

    return 0;
 }

Snapshots of the program and output:

Text Description automatically generated

Text Description automatically generated with medium confidence

Concatenation of Two Strings Without Using Library Function

Using “for” loop to copy the second string at the end of the first string.

#include<stdio.h>

#include<string.h>

 #define BUF_SIZE 256
 int main()
 {
    char S1[BUF_SIZE],S2[BUF_SIZE];   /* Declare the buffers S1, S2 for both the string*/
    int length = 0,i,j;                        /*Variables needed for loop traversal*/

    printf("Enter the first string");         /* Print user message to enter first string */
    fgets(S1,BUF_SIZE,stdin);          /* user input string will be stored in S1*/
    S1[strlen(S1)-1] = '\0';

    printf(" Enter the second string"); /* Print user message to enter Second string */
    fgets(S2,BUF_SIZE,stdin); /* user input string will be stored in S2*/
    S2[strlen(S2)-1] = '\0';
    /* Traverse first string to find the length of S1*/
    for(i=0;S1[i]!='\0';i++)
{  
        length = length+1;
}

/*length will have the end of the S1, start from length and copy the whole S2 into S1*/
    for(i=length,j=0;S2[j]!='\0';i++,j++)
{
        S1[i]=S2[j];
        S1[i]='\0';
}

/*Print the S1 , concatenated result */
    printf("\n Concatenated string is %s\n\n",S1);
    return 0;
   }

Snapshots of the program and output:

Text Description automatically generated

Text Description automatically generated

Another Way of Without Library Function

Concatenation using recursion:

The function stringconcatenate() will be used to get the length of string1. If S2 is empty then a null character will be assigned to S2.

If null character is not assigned to S2 than add element of S2 in the end of S1 that is S1[i+j]=S2[j], this increases the value of i in the string.

A function will be called itself by passing the reformed strings(S1,S2) as an argument. It will be called again and again until the S2 is empty.

The concatenated S1 will be printed by main() as

#include<stdio.h>

#include<string.h>

#define BUF_SIZE 256

/* recursive function to implement string concatenation as per the above description */
   void stringconcatenate(char *S1,char *S2)
   {
    static int i=0;
    static  int j;
    j= strlen(S1);
    if(!S2[i])
    {
        S2[i]='\0';
     }
     else
     {
        S1[j] =S2[i];
         S1[j+1] = '\0';
        i++;
        stringconcatenate(S1,S2);
    }
     }
     int main()
    {
    char S1[BUF_SIZE],S2[BUF_SIZE];

    printf("Enter the value of first string:");   /* user message to input 1st string */
    fgets(S1,BUF_SIZE,stdin);        /* user input first string, store in S1 */
    S1[strlen(S1)-1] = '\0';

    printf("Enter the value of second string:"); /* user message to input 2nd string */
    fgets(S2,BUF_SIZE,stdin); /* user input first string, store in S2 */
    S2[strlen(S2)-1] = '\0';

    stringconcatenate(S1,S2);         /* Call the function with S1,S2 as parameters */

    printf("combination of strings ='%s'\n",S1);
    return 0;
     }

Snapshots of the program and output:

Text Description automatically generated

Text Description automatically generated

Concatenation by Using Functions

The function strconcatenate() is called by the main() to combine two strings.

The function gets the length of string1 by using stringlen(string1).

Adjoin the elements of string2[i] in string1[i+j]. This step will be repeated until the string is empty. Here, we adjoin the string2 to string1 in the end of string1.

Concatenated string(string 1) will be received by the end when all the iterations of for loop will be performed.

The main() prints the concatenated string S1

#include<stdio.h>

#include<string.h>

#define BUF_SIZE 256

/* function to implement string concatenation as per the above description */
   void strconcatenate(char *string1, char*string2)
   {
    int i;
    int j= strlen(string1);
    for(i=0; string 2[i];i++)
    {
        string1[i+j]= string2[i];
    }
    string1[i+j]= '\0';
    }
    int main()
    {
     char string1[BUF_SIZE],string2[BUF_SIZE];
    printf("Enter the first string:");  /* User message for 1st string */
    fgets(string1,BUF_SIZE,stdin);  /* User input second string , stored into string1 */
    string1[strlen(string1)-1] = '\0';

    printf("Enter the second string:");   /* User message for 2nd string */
    fgets(string2,BUF_SIZE,stdin);     /* User input second string , stored into string2 */
    string2[strlen(string2)-1] = '\0';

strconcatenate(string1,string2);  /* Call the function with string1 and string2 as arguments*/

    printf("Resultant string = %s'\n",string1);
     return 0;
     }

Snapshots of the program and output:

Text Description automatically generated

Text Description automatically generated

String Concatenation by Using memcpy

By using memcpy() function, the concatenation of string is done by copying word by word from one string buffer to the end of another string buffer where word size is 4 bytes considering we are running on 32 bit machine while when we do string concatenation by using string concatenation by using strcat() function, concatenation is done by copying byte by byte from one string buffer to another string buffer.

This approach is performance efficient.

The only consideration while using memcpy is to take care of ‘\0’.

C program to achieve the strcat with memcpy:

#include <stdio.h>

#include <string.h>

#define BUF_SIZE 256

Void strcat_memcpy(char *S1, char *S2)
{
    int length1, length2;
    length1 = strlen(S1);
    length2 = strlen(S2);
    memcpy(S1+length1,S2,length2);
}
int main()
{

     char string1[BUF_SIZE],string2[BUF_SIZE];
    printf("Enter the first string:");  /* User message for 1st string */
    fgets(string1,BUF_SIZE,stdin);  /* User input second string , stored into string1 */
    string1[strlen(string1)-1] = '\0';

    printf("Enter the second string:");   /* User message for 2nd string */
    fgets(string2,BUF_SIZE,stdin);     /* User input second string , stored into string2 */
    string2[strlen(string2)-1] = '\0';

strcat_memcpy(string1,string2);  /* Call the function with string1 and string2 as arguments*/

    printf("Resultant string = %s'\n",string1);
     return 0;

   
}

Snapshots of the program and output:

Text Description automatically generated

Text Description automatically generated

Conclusion:

With all this discussion we can conclude the string concatenation in C. We have seen many examples and sample programs for string concatenation. We will recall the main items: There are two ways, one with C standard and other is user defined way. User defined can further be of many types, depends on how user want to implement string concatenation.



from Linux Hint https://ift.tt/3itET7o

Post a Comment

0 Comments