🔎 Concatenate Strings in C (With & Without strcat)

⬅️ Back

🧑‍đŸ’ģ Tutorial: Concatenate Two Strings in C (With and Without strcat())

This tutorial teaches how to join (concatenate) two strings in C using:

  • ✅ Built-in function strcat()
  • 🛠️ Manual method (without string functions)

✅ Method 1: Using strcat() Function

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

int main() {
    char str1[200], str2[100];

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove newline if present
    size_t len1 = strlen(str1);
    if (len1 > 0 && str1[len1 - 1] == '\n') {
        str1[len1 - 1] = '\0';
    }

    size_t len2 = strlen(str2);
    if (len2 > 0 && str2[len2 - 1] == '\n') {
        str2[len2 - 1] = '\0';
    }

    strcat(str1, str2);  // Concatenate str2 to str1

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

    return 0;
}

📝 Explanation:

  • strcat() joins str2 to the end of str1.
  • fgets() reads strings with spaces.
  • Ensure the destination string (str1) has enough space.

🛠️ Method 2: Without Using strcat()

#include <stdio.h>

int main() {
    char str1[200], str2[100];
    int i = 0, j = 0;

    printf("Enter first string: ");
    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");
    fgets(str2, sizeof(str2), stdin);

    // Remove newline characters
    while (str1[i] != '\0') {
        if (str1[i] == '\n') {
            str1[i] = '\0';
            break;
        }
        i++;
    }

    while (str2[j] != '\0') {
        if (str2[j] == '\n') {
            str2[j] = '\0';
            break;
        }
        j++;
    }

    // Find end of str1
    i = 0;
    while (str1[i] != '\0') {
        i++;
    }

    // Append str2 to str1 manually
    j = 0;
    while (str2[j] != '\0') {
        str1[i] = str2[j];
        i++;
        j++;
    }
    str1[i] = '\0';  // End string

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

    return 0;
}

📝 Explanation:

  • This method finds the end of str1 manually.
  • Each character from str2 is appended one by one.
  • No string library functions are used.

📌 Summary

You can concatenate strings using strcat() or by manually copying each character. Manual logic helps understand how strings work in memory.

C programming, string concatenation, C string tutorial, strcat example, join strings in C, C programming without string functions, beginner C practice problems, manual string logic

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ