1. Computing & Technology

Discuss in my forum

C++ Programming Tutorial - C++ Strings

By , About.com Guide

1 of 10

Are C++ Strings Better than C Strings?
One of the most powerful features of C++ is its extensibility through templates. Nowhere is this better demonstrated than in the C++ string class. Although a template class at heart, it's part of the standard library (and resides in the std namespace).

You may feel that there is nothing wrong with C strings- there is a large body of code for that and printf() is easier to use than cout when it comes to formatting. Well the formatting is true, though there are ways round it such as the Boost printf() library but when it comes to code security, C loses out to C++. There have even been exploits with printf() format specifiers. If you have the option, C++ Strings are more powerful, often faster and certainly safer and easier to work with.

In the rest of this C++ programming tutorial, I'll show you how to work with C++ strings. Hopefully you'll be persuaded that thy are both easier and safer than C strings in your C++ applications.

A Brief Look at Templates

Templates in C++ is a complicated subject and one we will return to. They allow you to define functions and classes which work independently of the type that they will be used with. A classic example is a Vector, which is a dynamic array that can change size at runtime. You instantiate the vector for a type that you specify- so it may be a Vector of payroll records or ints.

In C++, strings are a template class that has been designed to be compatible with C strings (the char * type with a terminating '\0') as well as efficient. Technically string is a specialization of basic_string for type char. It's also a very efficient class and deliberately very general.

On the next page : Working With Strings

©2012 About.com. All rights reserved.

A part of The New York Times Company.