Jul 31, 2020

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

Ex: Write a C program to copy one string to another string without using strcpy() function.
How to copy one string to another string without using strcpy() function. C program to copy one string to another string without using strcpy() function.


Input from user:

Enter the string:
I love codeforhunger

Expected output:

First string: I love codeforhunger

Second string: I love codeforhunger




  Step by step logic of the given program:


1. Accept string from user declare varible say str1.

2. Declare another variable to store copy of first string, varible say str2.

3. Run while loop from 0 to end of string.

4. Inside the while loop for each character in str1 copy to str2 using:
str2[i]=str1[i];

5. After loop make sure the copied string ends with NULL character using: 
str2[i]= '\0';





  Program to copy one string to another string without using strcpy() function:

#include<stdio.h>
#include<string.h>
#define max 100

void main()
{
char str1[max],str2[max];//declare string of max size 100
int i=0;
    

printf("Enter the string:\n");
gets(str1);

/*Iterate loop till end of string*/
 while(str1[i]!='\0')
{
/*copy the string */
str2[i]=str1[i];
i++;
}
/*make sure that string is Null terminated*/ 
     str2[i]='\0';

printf("\nFirst string: %s",str2);
printf("\nSecond string: %s",str2);
}



Above program shows the following output:


C program to print given string in reverse order without using strrev()



No comments:

Post a Comment

If you have any doubts, please discuss here...