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

C++ Programming Tutorial - C++ Strings

By , About.com Guide

2 of 10

Working with C++ Strings

Using a string is easy. There are many ways to initialize it.
string s;
string *ps = new string("Hiya!") ;

const char sometext[]="A zero terminated string";
string ps=sometext;
A minor gotcha. Though string is in the <string> library, you can also access it via the std namespace, however cout may not work with it, as in this example below.
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
string str("Hello World!") ;
cout << str << endl;
}
You have to add this line with some compilers, eg Microsoft Visual C++ 6.0 and Microsoft Visual C++ 2005 but others may or may not need it.
#include <string>
Download Example 1

Example 1 shows a number of ways to initialize a string. The s4 string uses one of the overloads of the constructor to copy from the start of a C string to the specified character. And s6 is initialized to a string with 80 asterisks.

Because of the underlying templated nature of strings, you can divide string functions into plain functions and template ones. We'll look at the simpler functions first.

Working with C Strings

A C string is a zero terminated array of chars but the C++ string does without the extra terminating zero. Most likely it keeps track of the length internally but you should not make any assumptions about how the implementation works.

Getting a C string into a C++ string is very easy. This code from example 1 does just that. [

const char CString[]="A zero terminated C String";
string s3=CString;
s3="Another string";
string s4(CString,&CString[1]) ;

On the next page Working with C Strings continued.

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. Learn C++ Programming
  6. Working with C++ Strings

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

All rights reserved.