English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program to concatenate two strings

Comprehensive Collection of C Programming Examples

In this example, you will learn to manually concatenate two strings without using the strcat() function.

To understand this example, you should understand the followingC programmingTopic:

As you know, the best way to concatenate two strings in C programming is to usestrcat()function. However, in this example, we will manually concatenate two strings.

Concatenate two strings without using strcat()

#include <stdio.h>
int main() {
  char s1[10[0] = "programming ", s2[] = "is awesome";
  int length, j;
  //Concatenate s1store the length of the string in the length variable
  length = 0;
  while (s1[length] != '\0') {
    ++length;
  }
  //Concatenate s2connect to s1
  for (j = 0; s2[j] != '\0'; ++j, ++length) {
    s1[length] = s2[j];
  }
  //terminate s1string
  s1[length] = '\0';
  printf("Concatenated:  ");
  puts(s1);
  return 0;
}

Output Result

concatenated as: programming is awesome

Here, two strings s1and s2combined together, the result is stored in s1.

It is important to note that s1The length of the concatenated string should be sufficient to accommodate the string. If not, you may get unexpected output.

Comprehensive Collection of C Programming Examples