Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to copy one string to another string

C Code Example — String Programs

ADVERTISEMENT

C Program to copy one string to another string

Objective

Write a C program to copy one string into another string manually.

Algorithm / Approach

  1. Declare two character arrays: a (source) and b (destination).
  2. Read the source string.
  3. Use a while(a[i] != '\0') loop to copy each character: b[i] = a[i].
  4. CRITICAL: After the loop terminates, explicitly add the null terminator to the destination string: b[i] = '\0'.
  5. Print the copied string.
main.c
#include<stdio.h>
int main( ) {
 char a[100],b[100];
 int i=0;
 printf("Enter a String : ");
 gets(a);
 while(a[i] != '\0') {
  b[i] = a[i];
  i++;
 }
 b[i] = '\0';
 printf("Copied String = : ");
 i=0;
 while(b[i] != '\0') {
  printf("%c",b[i]);
  i++ ;
 }
 return 0;
}

Expected Output

Enter a String : C Prowess
Copied String = : C Prowess

Explanation of the Program

  • Instead of using the built-in strcpy() function from string.h, this program copies the data byte by byte.
  • Because we are copying character by character inside a loop, the loop stops right BEFORE the null terminator is copied. You MUST manually append the null terminator at the end of the destination array, otherwise printing it will result in trailing garbage data.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT