Here we are going to discuss a copy of a string i.e. Copy One String To Another String Using a Pointer.
The copy means in programming is “=” sign.
Why?
Because assignment operator takes the responsibility to assign from right value (rvalue to lvalue).
Now we are going to cover some common points –
What is a string?
A string is a sequence of characters which is accompanied by a null keyword (\0) at the end.
Syntax:
char s[10]="PROGRAM";
The above represents a string i.e., how a string is initialised.
For example:
P | R | O | G | R | A | M | \0 |
This is how a string gets represented in a program, as said above it is terminated by a null by default.
What is a copy of a string?
When a content of one string gets copied to another string having the same or more dimension as the original string, is known as a copy of a string.
For example:
char s[10]="CODING";
C | O | D | I | N | G | \0 |
char a[10];
Through the help of string keywords or techniques to copy a string, the content of string s gets copied to string a and holds the same value. This process is known as a copy of a string.
Now char a[10] holds:
C | O | D | I | N | G | \0 |
How to copy one string to one another using a pointer?
The string gets copied through the following instruction:
Explanation:
Step-1: We take two string one string *str1 is declared as a pointer and the other str2 empty string.
Step-2: We take a separate function “copystring” where we pass the two strings which are initialised in pointer variables *a and *b in the function.
Step-3: A while loop is used which runs until the value of *a reaches ‘\0’ null, and the variable is incremented by one *a++ in each phase of the loop.
Step-4: In the body of the while loop as the loop goes on each character is extracted and is stored in another string variable *b as (*b++=*a++).
Step-5: In the end, as the loop gets terminated a null is added at the end of the second string *b, which is denoted as the end of the string.
Step-6: Hence the second string str2 is printed to get the result of the copy operation.
Implementation Part of Above Explanation:
#include<stdio.h> void copystring(char *a, char *b); int main() { char *str1="CODING"; char str2[10]; copystring(str1,str2); printf("%s",str2); return 0; } void copystring(char *a, char *b) { while(*a!='\0') { *b++=*a++; } b="\0"; }
Output:
CODING
We can also use the string functions to copy the contents of the string and there may be different logics too. We have used a logic which supports the copy of strings successfully.
Please comment and share this article and if wants to improve WhatsApp us.