Program for String Copy in C

How to Copy String in C Programming?

String copy in C  is a basic function that is useful in many complex coding problems and projects. It is very important that a person know various ways in which a string can be copied to another string, either by using pre-defined functions or other various methods.

String-copy-in-C-image

Syntax 1:

Without using strcpy() function.

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

In this we are using a for loop to copy each character of the string into another empty string.

Working of Program :

In the program, we will require some numbers from the user or pre-defined variables depending on the program requirement to copy the string into another string.

Steps to String Copy in C:

  • Step 1: Start
  • Step 2: Declare the variable str1 and str2.
  • Step 3: Read input str1 from the user or predefine it according to the need.
  • Step 4: Use the syntax to copy the string into the empty string.
  • Step 5: Print the result of the program compiled.
  • Step 6:  Program end.

Problem 1:

Write a program to copy string without using strcpy().

Code:

Run
#include<stdio.h>
int main() {
    char str1[100], str2[100], i;
    printf("Enter string 1: ");
    fgets(str1, sizeof(str1), stdin);
    for (i = 0; str1[i] != '\0'; ++i) {
        str2[i] = str1[i];
    }
    str2[i] = '\0';
    printf("String 2: %s", str2);
    return 0;
}

Input:

Enter string 1: 4541478

Output:

String 2: 4541478

Syntax 2:

Using strcpy function to copy string in C.

char* strcpy(char* destination, const char* source);

Problem 2:

In the following program we will String copy using strcpy.

Code:

Run
#include<stdio.h>
#include<string.h>
int main() 
{
  char str1[25] = "Welcome to PrepInsta";
  char str2[25];
  // copying str1 to str2
  strcpy(str2, str1);
  puts(str2); 
  return 0;
}

Output:

Welcome to PrepInsta

Problem 3:

Write a program to copy string using pointers and post-increment using functions.

Code:

Run
#include<stdio.h>
#include<stdlib.h>
// Function to copy the string
void copyString(char* t, char* s)
{
    while (*t++ = *s++);
}
int main()
{
    char s2[25] = "Welcome to PrepInsta";
    char s1[25];
 
    // Function Call
    copyString(s1, s2);
    printf("%s", s1);
    return 0;
}

Output

Welcome to PrepInsta

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription