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

C Tutorial - Strings and Text Handling

By , About.com Guide

4 of 9

Using the Mem Functions in the string.h Library

The designers of C went down a different route to that of Basic so there are no Left(), Mid() and Right() functions, apart from those I created in example 1. Instead you get lower level operations for copying and comparing strings. As you may be outputting data, I also include sprintf from <stdio.h>. This is the same as printf with an extra first parameter that is a char *.

There are two types of functions in string.h. The str... functions such as strcat() and the mem... functions like memset(). Generally the Mem... functions are for a fixed size and have an extra parameter specifying it while the str... require the terminating '\0'. The mem... functions are not for string handling but for working with structs etc. I list them here for completeness.

  • void * memset(void *s,int c, size_t n) - sets n bytes of *s to the value c and returns s.
  • void memcpy(void *to, const void* from,size_t n) - copies a block of n bytes from *from to *to. Must not overlap.
  • void memmove(void *to, const void* from, size_t n) - copies a block of n bytes from *from to *to. Can overlap.
  • int memcmp(const void *s1, const void* s2, size_t n) - compares n bytes from *s1 with *s2. 0 if identical.
  • void * memchr(const void *s, int c, size_t n) - Searches n bytes of *s for the value c and returns a void * pointer to it if found, null if not found.
Download Example 2
This shows two badge structures initialized using memset() to clear all fields. The strcpy() function is used to assign strings and then memcpy() used to copy one badge into another before printing the values out. The memcpy() and memmove() functions are identical except that memmove() allows overlapping and memcpy() doesn't. Most CPUs have instructions to do fast copying and the compiler will use this if it can.

On the next page : A look at the char functions in ctype.h

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 Mem Functions in the string.h Library

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

All rights reserved.