Basic String Handling Functions
All the string handling functions are prototyped in:
#include <string.h>
The common functions are described below:
char *stpcpy (const char *dest,const char *src) -- Copy one string into another.
int strcmp(const char *string1,const char *string2) - Compare string1 and string2 to determine alphabetic order.
char *strcpy(const char *string1,const char *string2) -- Copy string2 to stringl.
char *strerror(int errnum) -- Get error message corresponding to specified error number.
int strlen(const char *string) -- Determine the length of a string.
char *strncat(const char *string1, char *string2, size_t n) -- Append n characters from string2 to stringl.
int strncmp(const char *string1, char *string2, size_t n) -- Compare first n characters of two strings.
char *strncpy(const char *string1,const char *string2, size_t n) -- Copy first n characters of string2 to stringl .
int strcasecmp(const char *s1, const char *s2) -- case insensitive version of strcmp().
int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version of strncmp().
The use of most of the functions is straightforward, for example:
char *str1 = "HELLO";
char *str2;
int length;
length = strlen("HELLO"); /* length = 5 */
(void) strcpy(str2,str1);
Note that both strcat() and strcopy() both return a copy of their first argument which is the destination array. Note the order of the arguments is destination array followed by source array which is sometimes easy to get the wrong around when programming.
The strcmp() function lexically compares the two input strings and returns:
Less than zero
-- if string1 is lexically less than string2
Zero
-- if string1 and string2 are lexically equal
Greater than zero
-- if string1 is lexically greater than string2
This can also confuse beginners and experience programmers forget this too.
The strncat(), strncmp,() and strncpy() copy functions are string restricted version of their more general counterparts. They perform a similar task but only up to the first n characters. Note the the NULL terminated requirement may get violated when using these functions, for example:
char *str1 = "HELLO";
char *str2;
int length = 2;
(void) strcpy(str2,str1, length); /* str2 = "HE" */
str2 is NOT NULL TERMINATED!! -- BEWARE