🧑‍đŸ’ģ Copy String in C Using strcpy() & Manual Method – Tutorial

⬅️ Back

🧑‍đŸ’ģ Tutorial: Copying a String in C

In this tutorial, you will learn how to copy a string in C programming using two methods:

  • Using the built-in strcpy() function
  • Manually copying characters without using any function

Method 1: Using strcpy() Function

The strcpy() function is provided by the <string.h> library and copies one string to another.

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

int main() {
    char source[] = "Hello World";
    char destination[50];  // Make sure destination array is big enough

    strcpy(destination, source);  // Copy source to destination

    printf("Copied String (using strcpy): %s\n", destination);

    return 0;
}

Explanation:

  • source contains the original string.
  • destination is the array where the string will be copied.
  • strcpy(destination, source); copies the string including the terminating null character.
  • Finally, the copied string is printed.

Method 2: Manual Copying Without strcpy()

This method copies the string character-by-character using a loop. This helps understand how copying works behind the scenes.

#include <stdio.h>

int main() {
    char source[] = "Hello World";
    char destination[50];
    int i = 0;

    // Copy characters one by one until null character
    while (source[i] != '\0') {
        destination[i] = source[i];
        i++;
    }

    destination[i] = '\0';  // Null-terminate the destination string

    printf("Copied String (manual copy): %s\n", destination);

    return 0;
}

Explanation:

  • A while loop copies each character from source to destination.
  • The loop stops when the null character '\0' is reached.
  • Then, the destination string is explicitly null-terminated.
  • The copied string is printed.

Summary

You can use the built-in strcpy() for easy and reliable copying, or manually copy characters if you want to understand the underlying process.

Both methods require that the destination array is large enough to hold the copied string plus the null terminator.

C programming, string copy in C, strcpy example, manual string copy, copy string without function, C tutorial, string functions in C, strcpy vs manual copy, C programming examples, beginner C programming

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

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