Pages

  • Home
  • About & Contact
  • Archive
  • C Programming Examples

01 March 2012

c program to copy one string to another without using strcpy [ using pointers ]

Here i am showing program to Copy Strings in 3 different ways in which two ways are to copy String without using strcpy.
String copy

C program to copy one String to another String using strcpy().
.For information on Strings and string functions in c



#include <stdio.h>
#include <string.h>
//#include<conio.h>
void main(void)
{
   char src[25],dest[25];
   //clrscr();
   printf("\nEnter the String which is to be copied to another String:");
   gets(src);
   strcpy(dest,src);
   printf("\nCopied String is %s",dest);
}

C program to copy one String to another String without using strcpy().


#include<stdio.h>
void main(void)
{
   char src[25],dest[25];
   int i=0;
   printf("\nEnter the String Which is to be copied ");
   gets(src);
   do
   {
dest[i]=src[i];
   }while(src[i++]!='\0');
   printf("\nCopied String is %s",dest);
}

C program to copy one String to another String without using strcpy() using pointers


#include<stdio.h>
void copy(char* ,char* );
void main(void)
{
   char src[25],dest[25];
   printf("\nEnter String to be copied to another String:");
   gets(src);
   copy(dest,src);  //1
   printf("\nCopied String is %s %s",dest,src);
}

void copy(char *s1,char *s2)
{
      while(*s2!='\0') //2
     {
   *s1=*s2;                               //3
    s1++;
    s2++;                                   //4
      }
      s1='\0';
}



Explanation:First program does not require any explanation as it just requires in-built strcpy().
Second and Third program have much similar logic.So i am showing the logic behind the third program
Assume
 Src String "Science\0" is to be copied into another String i.e dest.

Consider statement  //1  there we are Sending two parameter's they are the pointers.1st is the base address of String dest and 2nd is the base address of  String src.both are collected in character pointers s1 and s2 respectively.


Consider  statement  //2  here we are checking is s2 has reached the end of string i.e '\0'.

Now Statement //3 What we want to do now is to copy the contains of str2 to str1.
untill s2 reaches the end.

Statement //4 :Copying of s2 to s1 is done in loop and increments the pointer's untill s2 reaches its end.

Thus we get the the copied String 

Similar Programs:
c program to find length of string without using strlen function [ using pointers]

2 comments:

  1. can you explain why it is possible to copy a character without using STRCPY ?

    ReplyDelete
  2. thanks for the programs

    ReplyDelete

Back To Top