1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Strings and Text Handling

By , About.com Guide

7 of 9

Using the str Functions Continued

In example 4, the strlen() function counts the number of chars before the terminating zero so you must allocate enough space for the terminating zero in the combined string, hence the +1. The strcpy() function copies a into c, the strcat() appends b to c. The append starts exactly on the terminating zero of c after a was copied into it.

With strcmp(s1,s2) it returns an int result which is -1, 0 or +1. 0 is a match, i.e the same but -1 means that s1 is less than s2 and 1 means s1 is greater than s2. This comparison is based on the ASCII value of the first char of s1 compared to the first char of s2. If there are non standard letters used (i.e. foreign characters) then you should call strcoll() instead of strcmp().

Download Example 5

This is a longer example about 140 lines long. It reads a text file into a string buffer, extracts words from the text adding them to a list of unique words and counts how many times each word was found.

How It Works

Accept the ReadFile() function for now; file handling will be covered in the next C tutorial. This function reads in the file into a string buffer and returns -1 if the file isn't found, or the size of the file in bytes if it is. The buffer was set to a size big enough to hold the test file. Of course it would be better to get the file length from the file and allocate just enough memory to hold that.

The main structure is defined in the struct wordrec.

typedef char * string;

typedef struct wordrec * wordrecptr;
struct wordrec {
  string word;
  int count;
  wordrecptr next;
};

On the next page : More about Example 5

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Using the str Functions Continued

©2009 About.com, a part of The New York Times Company.

All rights reserved.