- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C Program to Copy One String to Another
In this tutorial, we will learn about how to copy one string to another in the C language, with and without using the library function strcpy(). At last, we will also learn how to copy strings using pointers. Let's first start with a copy string using the library function.
In C, use the strcpy() function to copy a string
To copy a string in C programming, you have to ask the user to enter the string to store it in the first string variable, say str1, and then copy it into the second string variable, say str2, using the strcpy() function of the string.h library. The function strcpy() takes two arguments. The value of the second argument gets copied to the first argument.
#include<stdio.h> #include<conio.h> #include<string.h> int main() { char str1[20], str2[20]; printf("Enter the string: "); gets(str1); printf("\nString 1 = %s", str1); strcpy(str2, str1); printf("\nString 2 = %s", str2); getch(); return 0; }
As the above program was written in the Code::Blocks IDE, here is the first screenshot of the sample run that you will also see on your output screen after running the program:
Now enter any string, such as fresherearth, and press the ENTER key to see the output shown here.This is the second snapshot of the sample run:
Here is another sample run, where the user enters any string that contains space:
Program Explained
- Get string input from the user using the gets() function.
- Before using the gets() function, include a string.h library function.
- Now copy the string into another variable, say str2, using the strcpy() function.
- The strcpy() function takes two arguments. The first argument is the target variable where the string is going to be copied.
- The second argument is the source variable. The value of this variable is initialized to the target variable.
- And finally, print the value of both variables.
As you can see from the previous program, I used the gets() function to get the string input. Because if we use the scanf() function and the user enters a string that contains spaces, then after the space all the string's values get skipped. For example, if the above program is replaced with the following program::
#include<stdio.h> #include<conio.h> int main() { char str1[20], str2[20]; printf("Enter the string: "); scanf("%s", str1); printf("\nString 1 = %s", str1); strcpy(str2, str1); printf("\nString 2 = %s", str2); getch(); return 0; }
Now let's take a sample run of the above program. In this case, I've provided the input as codes cracker. The string contains spaces; therefore, after the spaces, the rest of the string value gets skipped and only "codes" are initialized to the variable str1, as shown in the following snapshot:
As you can see from the above snapshot, only "codes" are initialized in the variable str1, and the value of str1 gets copied to the str2 variable. Therefore, the above program is correct only when the user doesn't supply any strings with spaces.
Copy a string in C without using the strcpy() function
This program performs the same function as the previous one, but without the use of the library function strcpy():
#include<stdio.h> #include<conio.h> int main() { char strOrig[100], strCopy[100], i; printf("Enter any string: "); gets(strOrig); for(i=0; strOrig[i]!='\0'; i++) strCopy[i] = strOrig[i]; strCopy[i] = '\0'; // do not forget to set a null-terminated character at the end of string printf("\nString 1 = %s", strOrig); printf("\nString 2 = %s", strCopy); getch(); return 0; }
Here is the final snapshot of the first sample run:
Here is the final snapshot of the second sample run:
Program Explained
- Get a string value using the gets() function.
- Start the for loop at the first character of the given string, strOrig, and continue until the null terminating character ('\0') occurs.
- Inside the for loop, copy each and every character of the given string, say strOrig, to any string, say strCopy, one by one.
- After exiting the for loop, insert a null-terminated character ('\0') at the end of the string (strCopy), into which all the characters of the given string (strOrig) are copied.
- Now print the value of both strings.
Using a Pointer to Copy a String in C
Now, let's make the same program with a pointer:
#include<stdio.h> #include<conio.h> void copystr(char *, char *); int main() { char sourceStr[50], targetStr[50]; printf("Enter the string: "); gets(sourceStr); printf("\nString 1 = %s", sourceStr); copystr(targetStr, sourceStr); printf("\nString 2 = %s", targetStr); getch(); return 0; } void copystr(char *targetString, char *sourceString) { while(*sourceString) { *targetString = *sourceString; sourceString++; targetString++; } *targetString = '\0'; }
Here is the sample run:
Now enter any string, say "fresherearth," and press the ENTER key to see the output as given in the second screenshot here:
Program Explained
- Here we've created a function named copystr() that has two pointer arguments.
- The first argument is responsible for the target string, and the second one is for the source string.
- After calling the function copystr(), the target string and source string get passed as arguments.
- And we know that the source string holds the value that the user enters at runtime. But the target string has some garbage values by default.
- Now we've created a while loop inside the function that runs before the source string comes to its null-terminated character, that is, '\0' (or runs until the last character of the string).
- Inside the loop, we have copied each character (one by one) of the source string into the target string.
- After copying or initializing, we have incremented both the pointer variables for target and source strings.
- After completing the while loop, all the characters of the source string get copied to the target variable.
- As we have used a pointer here, we only have to output the value of both strings.
- Never forget to end the targetString pointer variable with a null terminating character ('\0').
The same program in different languages
« Previous Program Next Program »