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

C Tutorial - Strings and Text Handling

By , About.com Guide

6 of 9

Using the str Functions

There are quite a number of these but you'll probably only need these that are listed below
  • strcat() - concatenate two strings.
  • strcpy() - copy a string (handy for doing string assignments).
  • strcmp() - compare two strings.
  • strlen() - return the length of a string- this does not include the terminating zero.
  • strchr() - find a character in a string searching from left.
You also get strn.. versions of the first three (not strlen( and strchr) with an extra parameter size_t n
  • strncat().
  • strncpy().
  • strncmp().
These limit the operation to the first n chars. For instance strncat() appends a maximum of n chars from a string to another string.

Memory Management

You are responsible for making sure that strings are properly allocated and freed. For instance this
string a="A very Long String";
string b=strcat(a," and now even longer!") ;
While it looks ok is a guaranteed disaster. The first line executes fine but the second takes exception. The strcat() function does not allocate any memory. The compiler would perceive this text as being read-only so it's probably located somewhere that cannot be written to. In this case you must allocate enough space to store the combined strings.

Example 4 demonstrates this correctly:

Download Example 4.

#include "stdlib.h"
#include <stdio.h>
#include <string.h>

typedef char * string;

int main(int argc, char* argv[])
{

  string a="A very Long String";
  string b=" and now even longer!";
  string c=malloc(strlen(a) + strlen(b)+1) ; /* +1 DFTTZ! */
  strcpy(c,a) ;
  strcat(c,b) ;
  printf("c = %s",c) ;
  free(c) ;
  return 0;
}

On the next page - More About This Example

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

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

All rights reserved.