Concatenate Two Strings Without Using strcat()

C Programming Language String functions in C (Article) String functions in C (Program)

406

Program:

#include <stdio.h>
int main() {
  char s1[100] = "programming ", s2[] = "is awesome";
  int length, j;

  // store length of s1 in the length variable
  length = 0;
  while (s1[length] != '\0') {
    ++length;
  }

  // concatenate s2 to s1
  for (j = 0; s2[j] != '\0'; ++j, ++length) {
    s1[length] = s2[j];
  }

  // terminating the s1 string
  s1[length] = '\0';

  printf("After concatenation: ");
  puts(s1);

  return 0;
}

Output:

After concatenation: programming is awesome

Explanation:

Here, two strings s1 and s2 and concatenated and the result is stored in s1.

It's important to note that the length of s1 should be sufficient to hold the string after concatenation. If not, you may get unexpected output.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.