The document summarizes common C string handling functions from the <string.h> standard library header. It provides descriptions and examples of functions like strcat, strchr, strcmp, strcpy, strlen, strncat, and strncmp. It also includes public domain implementations of many of these functions.
Download as DOC, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
131 views
String Fun C
The document summarizes common C string handling functions from the <string.h> standard library header. It provides descriptions and examples of functions like strcat, strchr, strcmp, strcpy, strlen, strncat, and strncmp. It also includes public domain implementations of many of these functions.
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19
[edit] Strings
A string in C is merely an array of characters. The length of a string is determined by a
terminating null character: '\0'. So, a string with the contents, say, "abc" has four characters: 'a', 'b', 'c', and the terminating null character. The terminating null character has the value zero. [edit] The <string.h> Standard Header Because programmers find raw strings cumbersome to deal with, they wrote the code in the <string.h> library. t represents not a concerted design effort but rather the accretion of contributions made by various authors over a span of years. !irst, three types of functions e"ist in the string library: the mem functions manipulate se#uences of arbitrary characters without regard to the null character$ the str functions manipulate null%terminated se#uences of characters$ the strn functions manipulate se#uences of non%null characters. [edit] The more commonly-used string functions The nine most commonly used functions in the string library are: strcat % concatenate two strings strchr % string scanning operation strcmp % compare two strings strcpy % copy a string strlen % get string length strncat % concatenate one string with part of another strncmp % compare parts of two strings strncpy % copy part of a string strrchr % string scanning operation [edit] The strcat function char *strcat(char * restrict s1, const char * restrict s2); Some people recommend using strncat() or strlcat() instead of strcat, in order to avoid buffer overflow. The strcat() function shall append a copy of the string pointed to by s2 &including the terminating null byte' to the end of the string pointed to by s1. The initial byte of s2 overwrites the null byte at the end of s1. f copying ta(es place between ob)ects that overlap, the behavior is undefined. The function returns s1. This function is used to attach one string to the end of another string. t is imperative that the first string &s1' have the space needed to store both strings. *"ample: incl!"e <st"io.h> incl!"e <string.h> ... static const char *colors#$ % &"'e"","(range",")ello*","+reen",",l!e","-!rple" .; static const char **i"ths#$ % &"/hin","0e"i!m","/hic1",",ol"" .; ... char pen/e2t#20$; ... int pen3olor % 4, pen/hic1ness % 2; strcpy(pen/e2t, colors#pen3olor$); strcat(pen/e2t, *i"ths#pen/hic1ness$); print5("0y pen is 6s\n", pen/e2t); 77 prints '0y pen is +reen/hic1' Before calling strcat(), the destination must currently contain a null terminated string or the first character must have been initialized with the null character &e.g. pen/e2t#0$ % '\0';'. The following is a public%domain implementation of strcat: incl!"e <string.h> 7* strcat *7 char *(strcat)(char *restrict s1, const char *restrict s2) & char *s % s1; 7* 0o8e s so that it points to the en" o5 s1. *7 *hile (*s 9% '\0') s::; 7* 3opy the contents o5 s2 into the space at the en" o5 s1. *7 strcpy(s, s2); ret!rn s1; . [edit] The strchr function char *strchr(const char *s, int c); The strchr() function shall locate the first occurrence of c &converted to a char' in the string pointed to by s. The terminating null byte is considered to be part of the string. The function returns the location of the found character, or a null pointer if the character was not found. This function is used to find certain characters in strings. At one point in history, this function was named in"e2. The strchr name, however cryptic, fits the general pattern for naming. The following is a public%domain implementation of strchr: incl!"e <string.h> 7* strchr *7 char *(strchr)(const char *s, int c) & 7* ;can s 5or the character. <hen this loop is 5inishe", s *ill either point to the en" o5 the string or the character *e *ere loo1ing 5or. *7 *hile (*s 9% '\0' == *s 9% (char)c) s::; ret!rn ( (*s %% c) > (char *) s ? @ABB ); . [edit] The strcmp function int strcmp(const char *s1, const char *s2); A rudimentary form of string comparison is done with the strcmp&' function. t ta(es two strings as arguments and returns a value less than zero if the first is le"ographically less than the second, a value greater than zero if the first is le"ographically greater than the second, or zero if the two strings are e#ual. The comparison is done by comparing the coded &ascii' value of the chararacters, character by character. This simple type of string comparison is nowadays generally considered unacceptable when sorting lists of strings. +ore advanced algorithms e"ist that are capable of producing lists in dictionary sorted order. They can also fi" problems such as strcmp&' considering the string ,Alpha-, greater than ,Alpha.-,. &n the previous e"ample, ,Alpha-, compares greater than ,Alpha.-, because /-/ comes after /./ in the character set.' 0hat we/re saying is, don/t use this strcmp() alone for general string sorting in any commercial or professional code. The strcmp() function shall compare the string pointed to by s1 to the string pointed to by s2. The sign of a non%zero return value shall be determined by the sign of the difference between the values of the first pair of bytes &both interpreted as type !nsigne" char' that differ in the strings being compared. 1pon completion, strcmp() shall return an integer greater than, e#ual to, or less than 2, if the string pointed to by s1 is greater than, e#ual to, or less than the string pointed to by s2, respectively. Since comparing pointers by themselves is not practically useful unless one is comparing pointers within the same array, this function le"ically compares the strings that two pointers point to. This function is useful in comparisons, e.g. i5 (strcmp(s, "*hate8er") %% 0) 7* "o something *7 ; The collating se#uence used by strcmp() is e#uivalent to the machine/s native character set. The only guarantee about the order is that the digits from '0' to 'C' are in consecutive order. The following is a public%domain implementation of strcmp: incl!"e <string.h> 7* strcmp *7 int (strcmp)(const char *s1, const char *s2) & !nsigne" char !c1, !c2; 7* 0o8e s1 an" s2 to the 5irst "i55ering characters in each string, or the en"s o5 the strings i5 they are i"entical. *7 *hile (*s1 9% '\0' == *s1 %% *s2) & s1::; s2::; . 7* 3ompare the characters as !nsigne" char an" ret!rn the "i55erence. *7 !c1 % (*(!nsigne" char *) s1); !c2 % (*(!nsigne" char *) s2); ret!rn ((!c1 < !c2) > D1 ? (!c1 > !c2)); . [edit] The strcpy function char *strcpy(char *restrict s1, const char *restrict s2); Some people recommend always using strncpy() instead of strcpy, to avoid buffer overflow. The strcpy() function shall copy the C string pointed to by s2 &including the terminating null byte' into the array pointed to by s1. f copying ta(es place between ob)ects that overlap, the behavior is undefined. The function returns s1. There is no value used to indicate an error: if the arguments to strcpy() are correct, and the destination buffer is large enough, the function will never fail. *"ample: incl!"e <st"io.h> incl!"e <string.h> 7* ... *7 static const char *pen/ype%"ro!n""; 7* ... *7 char pen/e2t#20$; 7* ... *7 strcpy(pen/e2t, pen/ype); mportant: 3ou must ensure that the destination buffer &s1' is able to contain all the characters in the source array, including the terminating null byte. 4therwise, strcpy() will overwrite memory past the end of the buffer, causing a buffer overflow, which can cause the program to crash, or can be e"ploited by hac(ers to compromise the security of the computer. The following is a public%domain implementation of strcpy: incl!"e <string.h> 7* strcpy *7 char *(strcpy)(char *restrict s1, const char *restrict s2) & char *"st % s1; const char *src % s2; 7* Eo the copying in a loop. *7 *hile ((*"st:: % *src::) 9% '\0') ; 7* /he bo"y o5 this loop is le5t empty. *7 7* 'et!rn the "estination string. *7 ret!rn s1; . [edit] The strlen function siFeGt strlen(const char *s); The strlen() function shall compute the number of bytes in the string to which s points, not including the terminating null byte. t returns the number of bytes in the string. 5o value is used to indicate an error. The following is a public%domain implementation of strlen: incl!"e <string.h> 7* strlen *7 siFeGt (strlen)(const char *s) & const char *p % s; 7* Boop o8er the "ata in s. *7 *hile (*p 9% '\0') p::; ret!rn (siFeGt)(p D s); . [edit] The strncat function char *strncat(char *restrict s1, const char *restrict s2, siFeGt n); The strncat() function shall append not more than n bytes &a null byte and bytes that follow it are not appended' from the array pointed to by s2 to the end of the string pointed to by s1. The initial byte of s2 overwrites the null byte at the end of s1. A terminating null byte is always appended to the result. f copying ta(es place between ob)ects that overlap, the behavior is undefined. The function returns s1. The following is a public%domain implementation of strncat: incl!"e <string.h> 7* strncat *7 char *(strncat)(char *restrict s1, const char *restrict s2, siFeGt n) & char *s % s1; 7* Boop o8er the "ata in s1. *7 *hile (*s 9% '\0') s::; 7* s no* points to s1's trailing n!ll character, no* copy !p to n bytes 5rom s2 into s1 stopping i5 a n!ll character is enco!ntere" in s2. Ht is not sa5e to !se strncpy here since it copies IJK3/B) n characters, @ABB pa""ing i5 necessary. *7 *hile (n 9% 0 == (*s % *s2::) 9% '\0') & nDD; s::; . i5 (*s 9% '\0') *s % '\0'; ret!rn s1; . [edit] The strncmp function int strncmp(const char *s1, const char *s2, siFeGt n); The strncmp() function shall compare not more than n bytes &bytes that follow a null byte are not compared' from the array pointed to by s1 to the array pointed to by s2. The sign of a non%zero return value is determined by the sign of the difference between the values of the first pair of bytes &both interpreted as type !nsigne" char' that differ in the strings being compared. See strcmp for an e"planation of the return value. This function is useful in comparisons, as the strcmp function is. The following is a public%domain implementation of strncmp: incl!"e <string.h> 7* strncmp *7 int (strncmp)(const char *s1, const char *s2, siFeGt n) & !nsigne" char !c1, !c2; 7* @othing to compare> 'et!rn Fero. *7 i5 (n %% 0) ret!rn 0; 7* Boop, comparing bytes. *7 *hile (nDD > 0 == *s1 %% *s2) & 7* H5 *e'8e r!n o!t o5 bytes or hit a n!ll, ret!rn Fero since *e alrea"y 1no* *s1 %% *s2. *7 i5 (n %% 0 LL *s1 %% '\0') ret!rn 0; s1::; s2::; . !c1 % (*(!nsigne" char *) s1); !c2 % (*(!nsigne" char *) s2); ret!rn ((!c1 < !c2) > D1 ? (!c1 > !c2)); . [edit] The strncpy function char *strncpy(char *restrict s1, const char *restrict s2, siFeGt n); The strncpy() function shall copy not more than n bytes &bytes that follow a null byte are not copied' from the array pointed to by s2 to the array pointed to by s1. f copying ta(es place between ob)ects that overlap, the behavior is undefined. f the array pointed to by s2 is a string that is shorter than n bytes, null bytes shall be appended to the copy in the array pointed to by s1, until n bytes in all are written. The function shall return s.$ no return value is reserved to indicate an error. t is possible that the function will not return a null%terminated string, which happens if the s2 string is longer than n bytes. The following is a public%domain version of strncpy: incl!"e <string.h> 7* strncpy *7 char *(strncpy)(char *restrict s1, const char *restrict s2, siFeGt n) & char *"st % s1; const char *src % s2; 7* 3opy bytes, one at a time. *7 *hile (n > 0) & nDD; i5 ((*"st:: % *src::) %% '\0') & 7* H5 *e get here, *e 5o!n" a n!ll character at the en" o5 s2, so !se memset to p!t n!ll bytes at the en" o5 s1. *7 memset("st, '\0', n); brea1; . . ret!rn s1; . [edit] The strrchr function char *strrchr(const char *s, int c); strrchr is similar to strchr, e"cept the string is searched right to left. The strrchr() function shall locate the last occurrence of c &converted to a char' in the string pointed to by s. The terminating null byte is considered to be part of the string. ts return value is similar to strchr/s return value. At one point in history, this function was named rin"e2. The strrchr name, however cryptic, fits the general pattern for naming. The following is a public%domain implementation of strrchr: incl!"e <string.h> 7* strrchr *7 char *(strrchr)(const char *s, int c) & const char *last % @ABB; 7* H5 the character *e're loo1ing 5or is the terminating n!ll, *e M!st nee" to loo1 5or that character as there's only one o5 them in the string. *7 i5 (c %% '\0') ret!rn strchr(s, c); 7* Boop thro!gh, 5in"ing the last match be5ore hitting @ABB. *7 *hile ((s % strchr(s, c)) 9% @ABB) & last % s; s::; . ret!rn (char *) last; . [edit] The less commonly-used string functions The less%used functions are: memchr % !ind a byte in memory memcmp % Compare bytes in memory memcpy % Copy bytes in memory memmo8e % Copy bytes in memory with overlapping areas memset % Set bytes in memory strcoll % Compare bytes according to a locale%specific collating se#uence strcspn % 6et the length of a complementary substring strerror % 6et error message strpbr1 % Scan a string for a byte strspn % 6et the length of a substring strstr % !ind a substring strto1 % Split a string into to(ens str25rm % Transform string [edit] Copying functions [edit] The memcpy function 8oi" *memcpy(8oi" * restrict s1, const 8oi" * restrict s2, siFeGt n); The memcpy() function shall copy n bytes from the ob)ect pointed to by s2 into the ob)ect pointed to by s1. f copying ta(es place between ob)ects that overlap, the behavior is undefined. The function returns s1. Because the function does not have to worry about overlap, it can do the simplest copy it can. The following is a public%domain implementation of memcpy: incl!"e <string.h> 7* memcpy *7 8oi" *(memcpy)(8oi" * restrict s1, const 8oi" * restrict s2, siFeGt n) & char *"st % s1; const char *src % s2; 7* Boop an" copy. *7 *hile (nDD 9% 0) *"st:: % *src::; ret!rn s1; . [edit] The memmove function 8oi" *memmo8e(8oi" *s1, const 8oi" *s2, siFeGt n); The memmo8e() function shall copy n bytes from the ob)ect pointed to by s2 into the ob)ect pointed to by s1. Copying ta(es place as if the n bytes from the ob)ect pointed to by s2 are first copied into a temporary array of n bytes that does not overlap the ob)ects pointed to by s1 and s2, and then the n bytes from the temporary array are copied into the ob)ect pointed to by s1. The function returns the value of s1. The easy way to implement this without using a temporary array is to chec( for a condition that would prevent an ascending copy, and if found, do a descending copy. The following is a public%domain, though not completely portable, implementation of memmo8e: incl!"e <string.h> 7* memmo8e *7 8oi" *(memmo8e)(8oi" *s1, const 8oi" *s2, siFeGt n) & 7* note? these "on't ha8e to point to !nsigne" chars *7 char *p1 % s1; const char *p2 % s2; 7* test 5or o8erlap that pre8ents an ascen"ing copy *7 i5 (p2 < p1 == p1 < p2 : n) & 7* "o a "escen"ing copy *7 p2 :% n; p1 :% n; *hile (nDD 9% 0) *DDp1 % *DDp2; . else *hile (nDD 9% 0) *p1:: % *p2::; ret!rn s1; . [edit] Comparison functions [edit] The memcmp function int memcmp(const 8oi" *s1, const 8oi" *s2, siFeGt n); The memcmp() function shall compare the first n bytes &each interpreted as !nsigne" char' of the ob)ect pointed to by s1 to the first n bytes of the ob)ect pointed to by s2. The sign of a non%zero return value shall be determined by the sign of the difference between the values of the first pair of bytes &both interpreted as type !nsigne" char' that differ in the ob)ects being compared. The following is a public%domain implementation of memcmp: incl!"e <string.h> 7* memcmp *7 int (memcmp)(const 8oi" *s1, const 8oi" *s2, siFeGt n) & const !nsigne" char *!s1 % (const !nsigne" char *) s1; const !nsigne" char *!s2 % (const !nsigne" char *) s2; *hile (nDD 9% 0) & i5 (*!s1 9% *!s2) ret!rn (*!s1 < *!s2) > D1 ? :1; !s1::; !s2::; . ret!rn 0; . [edit] The strcoll and strxfrm functions int strcoll(const char *s1, const char *s2); siFeGt str25rm(char *s1, const char *s2, siFeGt n); The A5S C Standard specifies two locale%specific comparison functions. The strcoll function compares the string pointed to by s1 to the string pointed to by s2, both interpreted as appropriate to the B3G3(BBK/I category of the current locale. The return value is similar to strcmp. The str25rm function transforms the string pointed to by s2 and places the resulting string into the array pointed to by s1. The transformation is such that if the strcmp function is applied to the two transformed strings, it returns a value greater than, e#ual to, or less than zero, corresponding to the result of the strcoll function applied to the same two original strings. 5o more than n characters are placed into the resulting array pointed to by s1, including the terminating null character. f n is zero, s1 is permitted to be a null pointer. f copying ta(es place between ob)ects that overlap, the behavior is undefined. The function returns the length of the transformed string. These functions are rarely used and nontrivial to code, so there is no code for this section. [edit] Search functions [edit] The memchr function 8oi" *memchr(const 8oi" *s, int c, siFeGt n); The memchr() function shall locate the first occurrence of c &converted to an !nsigne" char' in the initial n bytes &each interpreted as !nsigne" char' of the ob)ect pointed to by s. f c is not found, memchr returns a null pointer. The following is a public%domain implementation of memchr: incl!"e <string.h> 7* memchr *7 8oi" *(memchr)(const 8oi" *s, int c, siFeGt n) & const !nsigne" char *src % s; !nsigne" char !c % c; *hile (nDD 9% 0) & i5 (*src %% !c) ret!rn (8oi" *) src; src::; . ret!rn @ABB; . [edit] The strcspn, strpbrk, and strspn functions siFeGt strcspn(const char *s1, const char *s2); char *strpbr1(const char *s1, const char *s2); siFeGt strspn(const char *s1, const char *s2); The strcspn function computes the length of the ma"imum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2. The strpbr1 function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2, returning a pointer to that character or a null pointer if not found. The strspn function computes the length of the ma"imum initial segment of the string pointed to by s1 which consists entirely of characters from the string pointed to by s2. All of these functions are similar e"cept in the test and the return value. The following are public%domain implementations of strcspn, strpbr1, and strspn: incl!"e <string.h> 7* strcspn *7 siFeGt (strcspn)(const char *s1, const char *s2) & const char *sc1; 5or (sc1 % s1; *sc1 9% '\0'; sc1::) i5 (strchr(s2, *sc1) 9% @ABB) ret!rn (sc1 D s1); ret!rn sc1 D s1; 7* terminating n!lls match *7 . incl!"e <string.h> 7* strpbr1 *7 char *(strpbr1)(const char *s1, const char *s2) & const char *sc1; 5or (sc1 % s1; *sc1 9% '\0'; sc1::) i5 (strchr(s2, *sc1) 9% @ABB) ret!rn (char *)sc1; ret!rn @ABB; 7* terminating n!lls match *7 . incl!"e <string.h> 7* strspn *7 siFeGt (strspn)(const char *s1, const char *s2) & const char *sc1; 5or (sc1 % s1; *sc1 9% '\0'; sc1::) i5 (strchr(s2, *sc1) %% @ABB) ret!rn (sc1 D s1); ret!rn sc1 D s1; 7* terminating n!lls "on't match *7 . [edit] The strstr function char *strstr(const char *haystac1, const char *nee"le); The strstr() function shall locate the first occurrence in the string pointed to by haystac1 of the se#uence of bytes &e"cluding the terminating null byte' in the string pointed to by nee"le. The function returns the pointer to the matching string in haystac1 or a null pointer if a match is not found. f nee"le is an empty string, the function returns haystac1. The following is a public%domain implementation of strstr: incl!"e <string.h> 7* strstr *7 char *(strstr)(const char *haystac1, const char *nee"le) & siFeGt nee"lelen; 7* 3hec1 5or the n!ll nee"le case. *7 i5 (*nee"le %% '\0') ret!rn (char *) haystac1; nee"lelen % strlen(nee"le); 5or (; (haystac1 % strchr(haystac1, *nee"le)) 9% @ABB; haystac1::) i5 (strncmp(haystac1, nee"le, nee"lelen) %% 0) ret!rn (char *) haystac1; ret!rn @ABB; . [edit] The strtok function char *strto1(char *restrict s1, const char *restrict "elimiters); A se#uence of calls to strto1() brea(s the string pointed to by s1 into a se#uence of to(ens, each of which is delimited by a byte from the string pointed to by "elimiters. The first call in the se#uence has s1 as its first argument, and is followed by calls with a null pointer as their first argument. The separator string pointed to by "elimiters may be different from call to call. The first call in the se#uence searches the string pointed to by s1 for the first byte that is not contained in the current separator string pointed to by "elimiters. f no such byte is found, then there are no to(ens in the string pointed to by s1 and strto1() shall return a null pointer. f such a byte is found, it is the start of the first to(en. The strto1() function then searches from there for a byte &or multiple, consecutive bytes' that is contained in the current separator string. f no such byte is found, the current to(en e"tends to the end of the string pointed to by s1, and subse#uent searches for a to(en shall return a null pointer. f such a byte is found, it is overwritten by a null byte, which terminates the current to(en. The strto1() function saves a pointer to the following byte, from which the ne"t search for a to(en shall start. *ach subse#uent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above. The strto1() function need not be reentrant. A function that is not re#uired to be reentrant is not re#uired to be thread%safe. Because the strto1() function must save state between calls, and you could not have two to(enizers going at the same time, the Single 1ni" Standard defined a similar function, strto1Gr(), that does not need to save state. ts prototype is this: char *strto1Gr(char *s, const char *"elimiters, char **lasts); The strto1Gr() function considers the null%terminated string s as a se#uence of zero or more te"t to(ens separated by spans of one or more characters from the separator string "elimiters. The argument lasts points to a user%provided pointer which points to stored information necessary for strto1Gr() to continue scanning the same string. n the first call to strto1Gr(), s points to a null%terminated string, "elimiters to a null% terminated string of separator characters, and the value pointed to by lasts is ignored. The strto1Gr() function shall return a pointer to the first character of the first to(en, write a null character into s immediately following the returned to(en, and update the pointer to which lasts points. n subse#uent calls, s is a null pointer and lasts shall be unchanged from the previous call so that subse#uent calls shall move through the string s, returning successive to(ens until no to(ens remain. The separator string "elimiters may be different from call to call. 0hen no to(en remains in s, a 5177 pointer shall be returned. The following public%domain code for strto1 and strto1Gr codes the former as a special case of the latter: incl!"e <string.h> 7* strto1Gr *7 char *(strto1Gr)(char *s, const char *"elimiters, char **lasts) & char *sbegin, *sen"; sbegin % s > s ? *lasts; sbegin :% strspn(sbegin, "elimiters); i5 (*sbegin %% '\0') & *lasts % ""; ret!rn @ABB; . sen" % sbegin : strcspn(sbegin, "elimiters); i5 (*sen" 9% '\0') *sen":: % '\0'; *lasts % sen"; ret!rn sbegin; . 7* strto1 *7 char *(strto1)(char *restrict s1, const char *restrict "elimiters) & static char *ssa8e % ""; ret!rn strto1Gr(s1, "elimiters, =ssa8e); . [edit] Miscellaneous functions These functions do not fit into one of the above categories. [edit] The memset function 8oi" *memset(8oi" *s, int c, siFeGt n); The memset() function converts c into !nsigne" char, then stores the character into the first n bytes of memory pointed to by s. The following is a public%domain implementation of memset: incl!"e <string.h> 7* memset *7 8oi" *(memset)(8oi" *s, int c, siFeGt n) & !nsigne" char *!s % s; !nsigne" char !c % c; *hile (nDD 9% 0) *!s:: % !c; ret!rn s; . [edit] The strerror function char *strerror(int errorco"e); This function returns a locale%specific error message corresponding to the parameter. 8epending on the circumstances, this function could be trivial to implement, but this author will not do that as it varies. The Single 1ni" System 9ersion : has a variant, strerrorGr, with this prototype: int strerrorGr(int errco"e, char *b!5, siFeGt b!5len); This function stores the message in b!5, which has a length of size b!5len. [edit] Examples To determine the number of characters in a string, the strlen() function is used: incl!"e <st"io.h> incl!"e <string.h> ... int length, length2; char *t!r1ey; static char *5lo*er% "begonia"; static char *gemstone%"r!by ";
length % strlen(5lo*er); print5("Bength % 6"\n", length); 77 prints 'Bength % N' length2 % strlen(gemstone);
t!r1ey % malloc( length : length2 : 1); i5 (t!r1ey) & strcpy( t!r1ey, gemstone); strcat( t!r1ey, 5lo*er); print5( "6s\n", t!r1ey); 77 prints 'r!by begonia' 5ree( t!r1ey ); . 5ote that the amount of memory allocated for /tur(ey/ is one plus the sum of the lengths of the strings to be concatenated. This is for the terminating null character, which is not counted in the lengths of the strings. [edit] Exercises .. The string functions use a lot of looping constructs. s there some way to portably unravel the loops; -. 0hat functions are possibly missing from the library as it stands now; [edit] String manipulation functions A string is a se#uence of zero or more characters surrounded in double #uotes, for e"ample "H am a string" "Oello <orl"9" "" 7* /he empty string *7 The double #uotes are not part of the string, they only serve to delimit it. The C programming language does not have a string data type, instead a string is stored as an array of characters with a 5177 &/<2/' character at the end. 0hen you need a character array to hold a string you need to declare the array to be one element larger than the string so that there is room for the 5177 character. !or e"ample, if you are declaring an array called answer to hold the value ==false// you should declare it as char ans*er#P$; *ven though there is no string type in C, strings are so useful that there is an e"tensive set of library functions for manipulating strings. To gain access to the string functions, you must include the following header file in your program: incl!"e <string.h> The most commonly%used string manipulation functions are as follows: Function name escription strcmp&s., s-' Compares s. to s-, returns 2 if s. >> s- strncmp&s., s-, int n' Compares the first n characters of s. and s- strlen&s.' 6et the length of the string s. strcpy&s., s-' Copies string s- into s. strncpy&s., s-, int n' Copies n characters from string s- into s. strcat&s., s-' Concatenates string s- onto the end of s. strncat&s., s-, int n' Append n characters from string s- to string sl !or e"ample: 7* I2ample 1 *7 incl!"e <st"io.h> incl!"e <st"lib.h> 7*/he ne2t line m!st al*ays be !se" *ith string 5!nctions*7 incl!"e <string.h> int main() & char reply#Q$; print5("Eo yo! *ant to r!n this program> #yes7no$ "); scan5("6s", reply); i5(strcmp(reply, "no") %% 0) 7* 0 means they are the same *7 e2it(1); else 7* /he rest o5 the program... *7 . 7* I2ample 2 *7 incl!"e <st"io.h> incl!"e <st"lib.h> incl!"e <string.h> int main() & char str#100$; print5("Inter a string\n"); scan5("6s", str); print5("/he length o5 (6s) is 6" \n", str, strlen(str) ); e2it(0); . 7* I2ample 4 *7 incl!"e <st"io.h> incl!"e <st"lib.h> incl!"e <string.h> int main() & char 5irstname#20$, s!rname#20$; char name#Q2$, nameGo55icial#Q2$; strcpy(5irstname, "/om"); strncpy(s!rname, "Rones", strlen("Rones"); strcpy(name, 5irstname); strcpy(nameGo55icial, s!rname); strcat(name, s!rname); strcat(nameGo55icial, s!rname); print5("name % 6s\n", name); print5("o55icial name % 6s\n", nameGo55icial); e2it(0); . Another very useful pair of string manipulation functions are sprintf&' and sscanf&' which are in the ?stdio.h@ library. They are similar to printf&' and scanf&' but instead of printing a formatted string to the screen &which we refer to as standard output or stdout' or reading a formatted string from the (eyboard &standard input or stdin' they print and read formatted strings toAfrom strings. !or e"ample: incl!"e <st"io.h> int main() & char str#20$; int i; print5("Inter an integer? "); scan5("6"", =i); sprint5(str, ")o! entere" 6"\n", i); print5("6s", str); e2it(0); . http:AAwww%teaching.physics.o".ac.u(AcomputingAhandboo(BcAnodeC..html
(Ebook) Gödel's Incompleteness Theorems (Elements in Philosophy and Logic) by Juliette Kennedy ISBN 9781108986991, 1108986994 - The full ebook set is available with all chapters for download