In C programming, strings are sequences of characters that end with a null character ('\0'). Copying one string to another is a common task, and there are different approaches to achieving this.
In this article, we will explore three methods to copy one string to another and provide examples for each approach.
Approach 1: Using a loop.
One of the simplest ways to copy a string is to use a loop that iterates through each character of the source string and assigns them to the corresponding positions in the destination string until the null character is encountered.
Below is the C program for the above approach:
// C program copy one string to another string using loop #include <stdio.h> void copyString(char source[], char destination[]) { int i = 0; while (source[i] != '\0') { destination[i] = source[i]; i++; } // Don't forget to add the null character at the end destination[i] = '\0'; } int main() { char source[] = "Hello, World!"; char destination[100]; //function call copyString(source, destination); printf("Source string: %s\n", source); printf("Copied string: %s\n", destination); return 0; }
Source string: Hello, World! Copied string: Hello, World!
Approach 2: Using strlen() Function.
Below is the C program for the above approach to copy string:
// C program copy one string to another string using strcpy #include <stdio.h> #include <string.h> int main() { char source[] = "Hello, Algolesson!"; char destination[100]; //built-in function to copy string strcpy(destination, source); printf("Source string: %s\n", source); printf("Copied string: %s\n", destination); return 0; }
Source string: Hello, Algolesson! Copied string: Hello, Algolesson!
Approach 3: Using Pointer Notation
// C program copy one string to another string using pointer #include <stdio.h> // function to copy string using pointer. void copyString(char *source, char *destination) { while (*source != '\0') { *destination = *source; source++; destination++; } *destination = '\0'; } int main() { char source[] = "Hello Coder!"; char destination[100]; copyString(source, destination); printf("Source string: %s\n", source); printf("Copied string: %s\n", destination); return 0; }
Source string: Hello Coder! Copied string: Hello Coder!
No comments:
Post a Comment