Copy String Without Using strcpy() in C

Exercise:

Write a C Program to copy string without using strcpy().

Click Here to View the Solution!
#include <stdio.h>
int main() {
    char str1[100], str2[100], i;
    printf("Enter string str1: ");
    fgets(str1, sizeof(str1), stdin);
    for (i = 0; str1[i] != '\0'; ++i) {
        str2[i] = str1[i];
    }
    str2[i] = '\0';
    printf("String str2: %s", str2);
    return 0;
}
Click Here to View the Output!
Enter string str1: This is a string
String str2: This is a string
Click Here to View the Explanation!
  • This program is used to copy a string without using the strcpy() function.
  • In main(), two string arrays s1 and s2 are declared of the size 100 along with a character type variable i.
  • The program requests the user to enter a string which is stored in the string array s1.
  • A for loop is initialized which iterates over the characters of s1 from i = 0 until the null character is encountered.
  • In each iteration, a character of the string s1 is copied to the string s2. The process continues until the iteration reaches the null character.
  • The string s2 is then terminated by assigning it the null character.
  • Finally, the string s2 is printed which holds the copy of the string s1.

%d bloggers like this: