String Processing Functions

The C library provides several useful functions for manipulating strings. The prototypes are in <string.h>. To illustrate these, lets try a few simple examples.

Task

Read lines of text from the standard input and print the longest line.

Approach

Our apporach can be the same as we have done many times to find the maximum - keep track of the max so far, and as we read each input, update the max so far if the new input is larger.

In this case, the data is strings instead of integers or floats, but tghe algorithm is the same:

     initialize the max
     get the first data
     while there is more data
          if the new data is larger than the max
                update the max
          get the next data

     return (print) the max
To implement this algorithm, we need to measure the length of a string. We could write our own utility to do this, or we can use strlen()
        int strlen(char *s);

which returns the number of characters in the string, s.

How do we update the max?

In this case the max that we want is the string with the longest length. We need to save the string itself. To do this we can copy the new data string into the max so far string.

How do we copy a string?

We could
       while(*max_so_far++ = *data++);
or we can use
        char *strcpy(char *target, char *src);

Two more things we need...

reading an writing the strings. We have already written a utility to read a string, get_string(). But once again, the C library can help as well:
     char *gets(char *s);

a function which reads a line of text from the standard input, replacing the '\n' with '\0' (NULL). It returns the pointer, s, or NULL if end of file or an error occurs.

To print the longest string, we can use

     printf("%s\n", max_so_far);
or use the library function
     int puts(char *s);

which has the same effect - print the string and a newline to the stanard output.

Putting it all together

We now have enough information to write the code:
     #include <string.h>
     #include <stdio.h>

     #define MAX_STR  200

     main()
     {  char data[MAX_STR];
        char max_so_far[MAX_STR] = "";

             strcpy(max_so_far,"");
             while(gets(data))
                  if(strlen(data) > strlen(max_so_far))
                       strcpy(max_so_far,data);

             puts(max_so_far);
     }

             

One more useful function - comparing strings

     int strcmp(char *s, char *t);

This function compares the strings s and t, character by character, and returns an integer:

What would these evaluate to?


Other string functions


[up] to C Library.