C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Concatenate two strings

C Program: Concatenate Two Strings Without strcat()

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str1[100], str2[100];

    int i = 0, j = 0;

 

    // Input first string

    printf("Enter the first string: ");

    gets(str1); // unsafe, use fgets() in practice

 

    // Input second string

    printf("Enter the second string: ");

    gets(str2);

 

    // Move to the end of the first string

    while (str1[i] != '\0') {

        i++;

    }

 

    // Copy second string to the end of first string

    while (str2[j] != '\0') {

        str1[i] = str2[j];

        i++;

        j++;

    }

 

    // Add null terminator

    str1[i] = '\0';

 

    // Display concatenated string

    printf("Concatenated string: %s\n", str1);

 

    return 0;

}

Output

 
INPUT :
Enter the first string: Hello
Enter the second string: World


OUTPUT 2 :
Concatenated string: HelloWorld

Explanation

  1. Two strings str1 and str2 are taken as input.
  2. The first loop moves to the end of str1.
  3. The second loop copies each character from str2 to str1 starting from the end.
  4. Finally, a null character ('\0') is added to terminate the concatenated string.

 

C Program: Concatenate Two Strings Without strcat()

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str1[100], str2[100];

    int i = 0, j = 0;

 

    printf("Enter the first string: ");

    fgets(str1, sizeof(str1), stdin);

 

    printf("Enter the second string: ");

    fgets(str2, sizeof(str2), stdin);

 

    // Remove newline characters (if present)

    while (str1[i] != '\0') {

        if (str1[i] == '\n') str1[i] = '\0';

        i++;

    }

 

    while (str2[j] != '\0' && str2[j] != '\n') {

        str1[i++] = str2[j++];

    }

 

    str1[i] = '\0';

 

    printf("Concatenated string: %s\n", str1);

 

    return 0;

}

Output

 
INPUT :
Enter the first string: Hello
Enter the second string: World


OUTPUT 2 :
Concatenated string: HelloWorld

Explanation

  1. Two strings str1 and str2 are taken as input.
  2. The first loop moves to the end of str1.
  3. The second loop copies each character from str2 to str1 starting from the end.
  4. Finally, a null character ('\0') is added to terminate the concatenated string.