Explanation
A string from one character array to another without using built-in string handling functions by iterating through the characters in the source array and copying them to the destination array one by one until you reach the null terminator ('\0').
#include <stdio.h>
void copyString(char *dest, const char *src) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0'; // Null-terminate the destination string
}
int main() {
char source[] = "Hello, World!";
char destination[20]; // Make sure the destination array is large enough
// Call the custom copyString function to copy the source to the destination
copyString(destination, source);
printf("Source: %s\n", source);
printf("Copied: %s\n", destination);
return 0;
}
In this program:
-
We define a custom function copyString that takes a destination (dest) and a source (src) string as arguments.
-
Inside the copyString function, we use a while loop to iterate through the characters of the source string until we reach the null terminator ('\0').
-
For each character in the source string, we copy it to the destination string.
-
After the loop, we explicitly null-terminate the destination string by adding a '\0' character at the end.
-
In the main function, we call the copyString function to copy the source string to the destination string.