Computer Programming
C Programming
C++ Programming
How To

How to write your own function for standard library functions strcat strcpy strcmp?

Answer

User Avatar
Wiki User
10/13/2009

Run through the char array

Though i cannot think of a reason do to it (why not use the available methods in the string.h ?) , it is possible to do it manually.
Loop through your character arrays and compare / copy.
Suppose you are char orig[100];
strcmp:
for (int i=0; orig[i] != 0; i++)
if (orig[i] != other[i]) return false;
return true; // because reached the end of the string.

and copy will be similar:
first get the length:
int length = 0;
for (int i=0; orig[i] !=0; i++, length++);
char *other = new char[length];
for (int i=0; i < length; i++)
other[i] = orig[i]; // will also copy the \0


Answer

Writing your own string functions is useful mainly for the challenge or practice. The versions that come with your compiler are most likely well optimized for your system, so you should not consider writing your own for performance reasons. That said, strcmp for one is simple enough to write:

int strcmp(const char *a, const char *b)
{
do
if (*a != *b) return *a - *b;
while (a++, *b++);

return 0;

}

strcpy is even simpler:

char *strcpy(char *dest, const char *src)
{
char *s = dest;
while (*dest++=*src++)
;

return s;

}

strcat is similar to strcpy, but it first finds the end of the dest string before copying the src string to it. I'll leave that as an exercise to the reader.