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

C Tutorial - Strings and Text Handling

By , About.com Guide

2 of 9

Text Processing- Char by Char

Unicode and C

C was written at a time when foreign characters were not much of a consideration. There were a couple of main character encodings in use- ASCII and EBCDIC. It wasn't until the 90s that Unicode started appearing and standard C does not work easily with Unicode. If you go on down that route, forget one char = one byte. It's two bytes or in some cases four bytes per character. This tutorial is not going to dwell on Unicode or use it; that's for a future tutorial but I wanted you to be aware of it. One good resource for anyone using Unicode in Visual C++ is Tex Texin's Unicode enabling Microsoft C/C++ Source Code.

Text Processing is by the Char

There is a <string.h> library that provides a set of string functions and well come to those shortly. If you choose not to use them, then you have to process text strings char by char. For some small applications that can be fun and very fast.

If you grew up with Basic, you might be familiar with Left(), Right() and Mid() functions as described below.I've used a simple typedef string as an alias for char * to improve readability.

  • Left(string Source,int NewLen) returns a string that is NewLen characters long, starting at the left
  • Right(string Source,int NewLen) returns a string that is NewLen characters long, starting at the right
  • Mid(string Source,int Start,int Length) returns a string that starts at Start and is Length characters long. Start is 0 based.
Download Example 1
Example 1 implements these in C. Because these functions allocate and return pointers, the caller of the function MUST free the pointer.

On the next page : Writing your own Functions

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. Text Processing- Char by Char

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

All rights reserved.