Wednesday 29 January 2014

Explain strcpy() and strncpy() function with example.

strcpy() function-It copies contents of one string to another.
Syntax
strcpy(destination,source)  ,where source string is copied to destination string.

Write a program to copy contents of one string to another by using strcpy().
#include<stdio.h>
#include<conio.h>
main()
{
    char s1[10],s2[10];
    clrscr();
    printf("Enter the string:");
    gets(s1);
    strcpy=(s2,s1);
    printf("\n Original string :%s",s1);
    printf("\n Duplicate string :%s",s2);
}
Output
Enter the string:Ragu
Original string:Ragu
Duplicate string:Ragu

strncpy() function-This function copies specified length of characters from source to destination string.
syntax
strncpy(destination,source,n) ,where n is the specified length

Write a program to copy source string to destination string with given length.
#include<stdio.h>
#include<conio.h>
main()
{
    char s1[10],s2[10];
    int n;
    clrscr();
    printf("Enter the source string:");
    gets(s1);
    printf("Enter the destination string:");
    gets(s2);
    printf("Enter number of characters to be replaced in destination string:");
    scanf("%d"&n);
    strcpy=(s2,s1,n);
    printf("\n Original string :%s",s1);
    printf("\n Duplicate string :%s",s2);
}
Output
Enter the source string:Wonderful
Enter the destination string:beautiful
Enter number of characters to be replaced in destination string:6
Enter the source string:Wonderful
Enter the destination string:wonderful

No comments:

Post a Comment