Copying strings
As strings are so important,
the standard C library provides many functions to examine and manipulate
strings.
However, C provides no basic string datatype,
so we often need to treat strings as array of characters.
Consider these implementations of functions
to copy one string into another:
// DETERMINE THE STRING LENGTH, THEN USE A BOUNDED LOOP
void my_strcpy(char destination[], char source[])
{
int length = strlen(source);
for(int i = 0 ; i < length ; ++i) {
destination[i] = source[i];
}
destination[length] = '\0';
}
|
|
// DO NOT WRITE STRING-PROCESSING LOOPS THIS WAY
void my_strcpy(char destination[], char source[])
{
int i;
for(i = 0 ; i < strlen(source) ; ++i) {
destination[i] = source[i];
}
destination[i] = '\0';
}
|
|
// USE AN UNBOUNDED LOOP, COPYING UNTIL THE NULL-BYTE
void my_strcpy(char destination[], char source[])
{
int i = 0;
while(source[i] != '\0') {
destination[i] = source[i];
i = i+1;
}
destination[i] = '\0';
}
|
|
// USE AN UNBOUNDED LOOP, COPYING UNTIL THE NULL-BYTE
void my_strcpy(char destination[], char source[])
{
int i = 0;
do {
destination[i] = source[i];
i = i+1;
} while(source[i-1] != '\0');
}
|
|
CITS2002 Systems Programming, Lecture 5, p8, 5th August 2024.
|