C program to copy one string to another string

Write a C program to copy one string to another string using loop. C program to copy one string to another without using inbuilt library function strcpy() and count total number of characters copied. How to copy one string to another and count total characters copied with and without using inbuilt string library function in C programming.

Write a C program to copy one string to another using strcpy() library function. How to use strcpy() library function.

Example:
Input string1: Hello World!
Output string2: Hello World!

Required knowledge

Basic C programming, Loop, String

Program to copy string without using strcpy()

/**
 * C program to copy one string to another string without using strcpy()
 */

#include <stdio.h>

int main()
{
    char text1[100], text2[100];
    int i;
    
    /* Reads the original string to be copied from user */
    printf("Enter any string: ");
    scanf("%s", &text1);
    
    /* Copies text1 to text2 character by character */
    i=0;
    while(text1[i]!='\0')
    {
        text2[i] = text1[i];
        i++;
    }

    //Makes sure that the string is NULL terminated
    text2[i] = '\0';

    printf("First string = %s\n", text1);
    printf("Second string = %s\n", text2);
    printf("Total characters copied = %d\n", i);

    return 0;
}


Output
Enter any string: CodeforWin
First string = CodeforWin
Second string = CodeforWin
Total characters copied = 10


Note: You can also use predefined string library function strcpy(dest-string, source-string) where the first parameter dest-string is the destination string to which the string is copied and source-string is the source string or original string. This function is present under string.h header file.


Program to copy string using strcpy()

/**
 * C program to copy one string to another string using strcpy()
 */

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

int main()
{
    char text1[100], text2[100];

    /* Reads the original string to be copied from user */
    printf("Enter any string: ");
    scanf("%s", &text1);


    /*
     * Copies text1 to text2 using strcpy()
     * Here first parameter of the function is destination string
     * And second is the source string
     */
    strcpy(text2, text1);

    printf("First string = %s\n", text1);
    printf("Second string = %s\n", text2);

    return 0;
} 


Output
Enter any string: CodeforWin
First string = CodeforWin
Second string = CodeforWin

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment