1. Goals for this week

  • More practice with strings in C (and using the readline library)

2. Starting Point Code

Start by creating a week09 directory in your inlab subdirectory and copying over some files:

$ cd ~/cs31/inlab
$ mkdir week09
$ cd week09
$ pwd
/home/you/cs31/inlab/week09
$ cp ~richardw/public/cs31/week09/* ./
$ ls

3. Strings and chars in C

Let’s look at the file str.c. This code contains some examples of manipulating strings (and individual chars in a string) in C.

Remember, that in C, a string is an array of char with a special terminating null character '\0' that signifies the end of the string. The array of chars can be statically or dynamically allocated (by calling malloc). One thing to remember is to allocate enough space for the terminating null character.

This code also shows an eample of using the readline library to read in a string entered by the user. There is some documentation about the readline library here: The readline library. Let’s look at the man page for readline and see what it does, how to call it, and what it returns:

$ man readline

The call to readline returns a string (allocated in heap space) to the caller containing the contents of the input line. It is the caller’s responsibility to free this returned string.

Let’s take a look at this code and see what it is doing. Note its uses the ctype and string library functions. C string library functions assume that the caller has allocated space for the result string (note the call to strcpy).

Some example use of string library functions:

strcat, strchr, strcmp, strcpy, strdup, strlen

Some example use of C library functions for testing char values:

isalnum, isdigit, isspace

Chapter 2.6.3 contains information about the string library and also C library functions for char values.

Their man pages will also give more information about how to use them.

$ man strcmp
$ man isspace

3.1. Try it out

  • In another window, compile and run this program to see what it is doing. Note when it is manipulating the individual char in the string (array of chars) and when it is treating it as a string (using strcpy, strlen).

Try running with some different input strings, for example:

hello 1 2 3
    hello   1   2   3
!@  hello  x%

4. Implementing your own string library

Proceed to Lab 7 where you will implement the string library functions discussed above.

5. Handy References