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

C Tutorial - Strings and Text Handling

By David Bolton, About.com

3 of 9

Writing your own Text Handling Functions

If you write your own functions, be sure to include error checking as I have done. All parameters should be sanity checked. A negative or zero length string doesn't make sense so the length is guaranteed to be 1. If the Source string is null then it returns a single space. The strings c and d check this.

Mid() is a little complicated and very hard to understand if you miss that there is a semi-colon at the end of first while! This is the complete loop. It moves Source forward character by character until it reaches the end of the string or Start becomes 0.

while (*Source++ && --Start) ;
When this starts, Source points to the A in "A Long string". When it exits, Source points to the L at position 2. The *Source is included so that it doesn't index past the end of a shorter string. Don't forget as well that in an &&, if the left hand is false, the right hand is not executed.

Right() actually measures the length of the string in the variable Length. This is a by product of incrementing Source until it points to the terminating zero. It's then used when decrementing Source to make sure that Source doesn't end up pointing to an address before the start of the string. The example for g tests this. It correctly prints out Short.

Lessons Learnt

  • Sanity check all parameters.
  • Test with extreme and idiotic cases!
  • Do not allow any pointers to move before the start of a string or after the terminating zero.
Of course as there is a <string.h> library provided, it makes sense not to reinvent this wheel.

On the next page : Using the mem functions in the string.h library

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

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Writing your own Text Handling Functions

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

All rights reserved.