1. Goals for this week

  • Practice using strings in C

  • Try 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 ~kwebb/public/cs31/week09/* ./
$ ls
Makefile  str.c

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.

In C, a string is a char array with a 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 shows an example of using the readline library to read in a string entered by the user. You can read some documentation on the readline library for further information, or you can look at the man page for readline and see what it does, how to call it, and see 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).

The C string library contains a number of useful functions. As part of lab 7, you will write some of them:

strcat, strchr, strcmp, strcpy, strdup, strlen, strstr

The ctype library contains 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