Using The STR Functions: Download Example 4
Using The STR Functions: Download Example 4
There are quite a number of these but you'll probably only need these that are listed below strcat() - concatenate two strings. strcpy() - copy a string (handy for doing string assignments). strcmp() - compare two strings. strlen() - return the length of a string- this does not include the terminating zero. strchr() - find a character in a string searching from left. You also get strn.. versions of the first three (not strlen( and strchr) with an extra parameter size_t n strncat(). strncpy(). strncmp(). These limit the operation to the first n chars. For instance strncat() appends a maximum of n chars from a string to another string. Memory Management You are responsible for making sure that strings are properly allocated and freed. For instance this string a="A very Long String"; string b=strcat(a," and now even longer!") ; While it looks ok is a guaranteed disaster. The first line executes fine but the second takes exception. The strcat() function does not allocate any memory. The compiler would perceive this text as being read-only so it's probably located somewhere that cannot be written to. In this case you must allocate enough space to store the combined strings. Example 4 demonstrates this correctly: Download #include #include #include Example 4. "stdlib.h" <stdio.h> <string.h>
typedef char * string; int main(int argc, char* argv[]) { string a="A very Long String"; string b=" and now even longer!"; string c=malloc(strlen(a) + strlen(b)+1) ; /* +1 DFTTZ! */ strcpy(c,a) ; strcat(c,b) ; printf("c = %s",c) ; free(c) ; return 0; }