Sams Teach Yourself C in 24 Hours (37 page)

BOOK: Sams Teach Yourself C in 24 Hours
3.66Mb size Format: txt, pdf, ePub

The for loop stops iterating when str2[i] evaluates to 0. By that time, the content of the string constant, Another string constant, has already been displayed on the screen.

The statement in line 22 assigns a string constant, “Assign a string to a pointer.”, : to the char pointer variable ptr_str. Also, a for loop is used to print out the string constant by putting every character in the string on the screen (see lines 23 and 24). Note that the dereferenced pointer *ptr_str is used to refer to one of the characters in the string 17 067231861x CH13 1/25/00 10:29 AM Page 212

212

Hour 13

constant. When the null character appended to the string is encountered, *ptr_str evaluates to 0, which causes the iteration of the for loop to stop. In line 24, the expression

*ptr_str++ moves the pointer to the next character of the string after the current character referred to by the pointer is fetched. In Hour 16, “Applying Pointers,” you’ll learn more about pointer arithmetic.

How Long Is a String?

Sometimes, you need to know how many bytes are taken by a string, since its length can be less than the length of its char array. In C, you can use a function called strlen() to measure the length of a string.

The
strlen()
Function

Let’s have a look of the syntax of the strlen() function.

The syntax for the strlen() function is

AX

#include

size_t strlen(const char *s);

YNTS

Here s is a char pointer variable. The return value from the function is the number

,

of bytes in the string, not counting the null character ‘\0’. size_t is a data type defined in the string.h header file. The size of the data type depends on the particular computer system. Note that string.h has to be included in your program

,

before you can call the strlen() function.

Listing 13.2 gives an example of using the strlen() function to measure string lengths.

LISTING 13.2

Measuring String Lengths

1: /* 13L02.c: Measuring string length */

2: #include

3: #include

4:

5: main()

6: {

7: char str1[] = {‘A’, ‘ ‘,

8: ‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’, ‘ ‘,

9: ‘c’, ‘o’, ‘n’, ‘s’, ‘t’, ‘a’, ‘n’, ‘t’, ‘\0’};

10: char str2[] = “Another string constant”;

11: char *ptr_str = “Assign a string to a pointer.”;

12:

13: printf(“The length of str1 is: %d bytes\n”, strlen(str1));

14: printf(“The length of str2 is: %d bytes\n”, strlen(str2));

15: printf(“The length of the string assigned to ptr_str is: %d bytes\n”, 16: strlen(ptr_str));

17 067231861x CH13 1/25/00 10:29 AM Page 213

Manipulating Strings

213

17: return 0;

18: }

I get the following output by running the executable, 13L02.exe, of the program in Listing 13.2.

The length of str1 is: 17 bytes

OUTPUT

The length of str2 is: 23 bytes

The length of the string assigned to ptr_str is: 29 bytes

In Listing 13.2, two char arrays, str1 and str2, and one pointer variable,
ANALYSIS
ptr_str, are declared and initialized in lines 7–11, respectively.

Then, the statement in line 13 obtains the length of the string constant held by str1, and prints out the result. From the result, you can see that the null character (\0) at the end of str1 is not counted by the strlen() function.

In lines 14–16, the lengths of the string constants referenced by str2 and ptr_str are measured and shown on the screen. The results indicate that the strlen() function does not count the null characters appended to the two string constants by the compiler, either.

Copying Strings with
strcpy()

If you want to copy a string from one array to another, you can copy each item of the first array to the corresponding element in the second array, or you can simply call the C

function strcpy() to do the job for you.

The syntax for the strcpy() function is

AX

#include

char *strcpy(char *dest, const char *src);

YNTS

Here the content of the string src is copied to the array referenced by dest. The

,

strcpy() function returns the value of src if it is successful. The header file

,

string.h must be included in your program before the strcpy() function is called.

13

The program in Listing 13.3 demonstrates how to copy a string from one array to another by either calling the strcpy() function or doing it yourself.

LISTING 13.3

Copying Strings

1: /* 13L03.c: Copying strings */

2: #include

3: #include

4:

5: main()

continues

17 067231861x CH13 1/25/00 10:29 AM Page 214

214

Hour 13

LISTING 13.3

continued

6: {

7: char str1[] = “Copy a string.”;

8: char str2[15];

9: char str3[15];

10: int i;

11:

12: /* with strcpy() */

13: strcpy(str2, str1);

14: /* without strcpy() */

15: for (i=0; str1[i]; i++)

16: str3[i] = str1[i];

17: str3[i] = ‘\0’;

18: /* display str2 and str3 */

19: printf(“The content of str2 using strcpy: %s\n”, str2);

20: printf(“The content of str3 without using strcpy: %s\n”, str3);

21: return 0;

22: }

After the executable, 13L03.exe, is created and run, the following output is displayed: The content of str2 using strcpy: Copy a string.

OUTPUT
The content of str3 without using strcpy: Copy a string.

Three char arrays, str1, str2, and str3, are declared in Listing 13.3. In addi-ANALYSIS tion, str1 is initialized with a string constant, “Copy a string.”, in line 7.

The statement in line 13 calls the strcpy() function to copy the content of str1 (including the null character appended by the compiler) to the array referenced by str2.

Lines 15–17 demonstrate another way to copy the content of str1 to an array referenced by str3. To do so, the for loop in lines 15 and 16 keeps copying characters of str1 to the corresponding elements in str3 one after another, until the null character (\0) appended by the compiler is encountered. When the null character is encountered, the str1[i] expression used as the condition of the for statement in line 15 evaluates to 0, which terminates the loop.

Because the for loop does not copy the null character from str1 to str3, the statement in line 17 appends a null character to the array referenced by str3. In C, it’s very important to make sure that any array that is used to store a string has a null character at the end of the string.

To prove that the string constant referenced by str1 has been copied to str2 and str3

successfully, the contents held by str2 and str3 are displayed on the screen. Note that 17 067231861x CH13 1/25/00 10:29 AM Page 215

Manipulating Strings

215

the string format specifier %s and the start addresses of str2 and str3 are passed to the printf() call in lines 19 and 20 to print out all characters, except the null character, stored in str2 and str3. The results displayed on the screen show that str2 and str3

have the exact same content as str1.

Reading and Writing Strings

Now let’s focus on how to read or write strings with the standard input and output streams—that is, stdin and stdout. In C, there are several functions you can use to deal with reading or writing strings. The following subsections introduce some of these functions.

The
gets()
and
puts()
Functions

The gets() function can be used to read characters from the standard input stream.

The syntax for the gets() function is

AX

#include

char *gets(char *s);

YNTS

Here the characters read from the standard input stream are stored in the character

,

array identified by s. The gets() function stops reading, and appends a null character \0 to the array, when a newline or end-of-file (EOF) character is encountered.

The function returns s if it concludes successfully. Otherwise, a null pointer is

,

returned.

The puts() function can be used to write characters to the standard output stream (that is, stdout) .

The syntax for the puts function is

AX

#include

int puts(const char *s);

YNTS

13

Here s refers to the character array that contains a string. The puts() function

,

writes the string to stdout. If the function is successful, it returns 0. Otherwise, a nonzero value is returned.

The puts() function appends a newline character to replace the null character at the

,

end of a character array.

Both the gets() and puts() functions require the header file stdio.h. In Listing 13.4, you can see the application of the two functions.

17 067231861x CH13 1/25/00 10:29 AM Page 216

216

Hour 13

LISTING 13.4

Using the gets() and puts() Functions

1: /* 13L04.c: Using gets() and puts() */

2: #include

3:

4: main()

5: {

6: char str[80];

7: int i, delt = ‘a’ - ‘A’;

8:

9: printf(“Enter a string less than 80 characters:\n”);

10: gets( str );

11: i = 0;

12: while (str[i]){

13: if ((str[i] >= ‘a’) && (str[i] <= ‘z’))

14: str[i] -= delt; /* convert to upper case */

15: ++i;

16: }

17: printf(“The entered string is (in uppercase):\n”);

18: puts( str );

19: return 0;

20: }

While running the executable 13L04.exe, I enter a line of characters (in bold below) from the keyboard and have the characters (all in uppercase) shown on the screen.

Enter a string less than 80 characters:

OUTPUT

This is a test.

The entered string is (in uppercase):

THIS IS A TEST.

The program in Listing 13.4 accepts a string of characters entered from the key-ANALYSIS board (that is, stdin), and then converts all lowercase characters to uppercase ones. Finally, the modified string is put back to the screen..

In line 6, a character array (str) is declared that can hold up to 80 characters. The gets() function in line 10 reads any characters entered by the user from the keyboard until the user presses the Enter key, which is interpreted as a newline character. The characters read in by the gets() function are stored into the character array indicated by str.

The newline character is not saved into str. Instead, a null character is appended to the array as a terminator.

The while loop in lines 12–15 has a conditional expression, str[i]. The while loop keeps iterating as long as str[i] evaluates to a nonzero value. Within the loop, the value of each character represented by str[i] is evaluated in line 13, to find out whether the 17 067231861x CH13 1/25/00 10:29 AM Page 217

Manipulating Strings

217

character is a lowercase character within the range of a through z. If the character is one of the lowercase characters, it is converted into uppercase by subtracting the value of an int variable, delt, from its current value in line 14. The delt variable is initialized in line 7 by the value of the expression ‘a’ - ‘A’, which is the difference between the numeric value of a lowercase character and its uppercase counterpart. In other words, by subtracting the difference of ‘a’ and ‘A’ from the lower case integer value, we obtain the uppercase integer value.

Then the puts() function in line 18 outputs the string with all uppercase characters to stdout, which goes to the screen by default. A newline character is appended by the puts() function when it encounters the null character at the end of the string..

Using
%s
with the
printf()
Function

We’ve used the printf() function in many program examples in this book. As you know, many format specifiers can be used with the printf() function to specify different display formats for data of various types.

For instance, you can use the string format specifier, %s, with the printf() function to display a character string saved in an array. (Refer to the example in Listing 13.3.) In the next section, the scanf() function is introduced as a way to read values of various data types with different format specifiers, including the format specifier %s.

The
scanf()
Function

The scanf() function provides another way to read strings from the standard input stream. Moreover, this function can actually be used to read various types of input data.

The formats of arguments to the scanf() function are quite similar to those used in the printf() function.

The syntax for the scanf() function is

AX

#include

int scanf(const char *format,...);

13

YNTS

Here various format specifiers can be included inside the format string referenced

,

by the char pointer variable format. If the scanf() function concludes successfully, it returns the number of data items read from stdin. If an error occurs, the scanf()

,

function returns EOF (end-of-file).

Using the string format specifier %s tells the scanf() function to continue reading characters until a space, a newline, a tab, a vertical tab, or a form feed is encountered.

Characters read by the scanf() function are stored into an array referenced by the corresponding argument. The array should be big enough to store the input characters.

Other books

Off the Grid by Karyn Good
Marked For Love (Mob Romance) by Grenier, Cristina
Camera Never Lies by Goddard, Elizabeth
Lethal Redemption by Richter Watkins