Skip to main content

Command Palette

Search for a command to run...

Concatenating Strings

Updated
•2 min read•View as Markdown

Program to concatenate the second string to the first one, provided that it fits within the memory allocated to the first string:

#include <stdio.h>
#define MAX 50

int main(){
    char str1[MAX];
    printf("Enter the string:");
    fgets(str1,MAX,stdin);
    printf("\nThe string is %s",str1);
    char str2[MAX];
    printf("Enter the string:");
    fgets(str2,MAX,stdin);

    int i=0,j=0;
    while (str1[++i]!='\0');
    i--; // to overwrite \n in the first string
    while(str2[j]!='\0'){
        str1[i]=str2[j];
        i++;
        j++;
    }
    str1[i]='\0';
    printf("The concatenated string is: %s",str1);
    puts(str1);
}

Output:

strcat and strncat from string.h

char* strcat(char* dest, const char* src);

strcat(dest, src) copies string src to the end of the string in array dest, adding a null character to the end.

For example, suppose that dest and src start out as follows.

After doing strcat(dest, src), the picture changes to the following.

The value returned by strcat(dest, src) is dest.

#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Hello ";
  char str2[] = "World!";

  // Concatenate str2 to str1 (the result is stored in str1)
  strcat(str1, str2);

  // Print str1
  printf("strcat output: %s\n\n", str1);

  return 0;
}

Output:

char* strncat(char* dest, const char* src,size_tn);

This is like strcat(dest, src), but at most n characters are copied from src.

#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Hello ";
  char str2[] = "World!";

  // Concatenate only the first four characters of str2 
  // to str1 (the result is stored in str1)
  strncat(str1, str2, 4);

  // Print str1
  printf("%s\n\n", str1);

  return 0;
}

Output:

15 views

More from this blog

P

Programming Tutorials

89 posts