1. Technology

C Tutorial - Strings and Text Handling


1 of 9

Strings and Things
In this tutorial I'll be looking in detail about text strings in C, how to work with them etc. First a recap.

There is no such thing as a string type in c. Other languages - C++, Delphi, C#, Java etc, all support a string type but C doesn't. In C, if you want to process text, you have to treat it as an array of char with a terminating \0. To define say a buffer big enough for 80 chars, this definition works.

char buffer[81];
Write this rule down and memorize it.
Don't forget the terminating 0 (DFTTZ). That's why the 80 char buffer is 81 chars in size. You can't assign a text string directly, so
buffer = "a test string";
does not work, but a char pointer string initialization is allowed.
char * myName = "David";
We'll see later how to assign a string at runtime using a built in function called strcpy(). Don't be tempted to add [] to the definition - this will create an array of pointers to a char, not a pointer to a char array! The code below allocates 3 strings and then prints them to the console.
char * name[3]={"alpha","beta","gamma"};
printf("%s %s %s",name[0],name[1],name[2]) ;
This printouts out
alpha beta gamma
One of the big problems with text processing in C is that you have to code every last detail and it's easy to make mistakes. Also, because you are generally working with pointers, it doesn't take too much effort to get a buffer overflow. Many vulnerabilities and exploits in operating system software have been due to buffer overflow exploits.

On the next page : Text Processing by the Char

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. C Tutorial - Strings and Text Handling

©2014 About.com. All rights reserved.