Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 489

17


abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvwxy
abcdefghijklmnopqrstuvwxyz
The ASCII codes for the letters b–z are 98–122. This program uses these ASCII
codes in its demonstration of strcat(). The forloop on lines 17–22 assigns
these values in turn to str2[0]. Because str2[1]is already the null character (line 15),
the effect is to assign the strings “b”,“c”, and so on to str2. Each of these strings is
concatenated with str1(line 20), and then str1is displayed on-screen (line 21).

Using the strncat()Function ......................................................................

The library function strncat()also performs string concatenation, but it lets you specify
how many characters of the source string are appended to the end of the destination
string. The prototype is
char *strncat(char *str1, const char *str2, size_t n);
Ifstr2contains more than ncharacters, the first ncharacters are appended to the end of
str1. If str2contains fewer than ncharacters, all of str2is appended to the end of
str1. In either case, a terminating null character is added at the end of the resulting
string. You must allocate enough space for str1to hold the resulting string. The function
returns a pointer to str1. Listing 17.6 uses strncat()to produce the same output as
Listing 17.5.

LISTING17.6 strncat.c. Using the strncat()function to concatenate strings
1: /* The strncat() function. */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: char str2[] = “abcdefghijklmnopqrstuvwxyz”;
7:
8: int main( void )
9: {
10: char str1[27];
11: int n;
12:
13: for (n=1; n< 27; n++)
14: {
15: strcpy(str1, “”);
16: strncat(str1, str2, n);
17: puts(str1);
18: }
19: return 0;
20: }

ANALYSIS

28 448201x-CH17 8/13/02 11:13 AM Page 489

Free download pdf