C Program to Copy String Without Using strcpy() | c programming code examples

C Topics C strcpy() Sort Elements in Lexicographical Order (Dictionary Order) String Manipulations In C Programming Using Library Functions C Program

To understand this example, you should have the knowledge of the following C programming topics:

·       C Pointers

·       Relationship Between Arrays and Pointers

·       C Pointers

·       C Pass Addresses and Pointers

·       C Dynamic Memory Allocation

·       C Programming Strings

As you know, the best way to copy a string is by using the strcpy() function. However, in this example, we will copy a string manually without using the strcpy() function.

Copy String Without Using strcpy()

#include <stdio.h>
int main() {
    char s1[100], s2[100], i;
    printf("Enter string s1: ");
    fgets(s1, sizeof(s1), stdin);

    for (i = 0; s1[i] != '\0'; ++i) {
        s2[i] = s1[i];
    }

    s2[i] = '\0';
    printf("String s2: %s", s2);
    return 0;
}

Output

Enter string s1: Hey fellow programmer.
String s2: Hey fellow programmer.

The above program copies the content of string s1 to string s2 manually.

Labels : #c ,#code ,#examples ,

Post a Comment