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

C++ Programming Tutorial - C++ Strings

By David Bolton, About.com

5 of 10

Using String Functions - An Example

Download Example 3

This demos these string functions find(), insert(), append() and replace() plus swap() for swapping this string with another, and substr() for getting part of a string.

substr() works with 0, 1 or 2 parameters as both parameters have defaults. The equivalent of the Basic string functions Left(), Mid() and Right() are

  • Left(string,len) - substr(0,len)
  • Mid(string,startpos,len) - substr(startpos,len)
  • Right(string,len) - substr( size()-startpos+1, len)
The max_size() function returns the longest string possible, just less than the static const value string::npos that is returned if a call to find() fails. npos is the unsigned equivalent of -1. This is a magic number that's always returned for failed searches. It will always be bigger than max_size().

About Example 3

The first loop indexes a string with the at() function. Then s1 is created as a 10000 long string of spaces. Both reserve() and resize() affect the capacity() before erasing the string and checking if it's empty by calling empty()

Then it uses strings s3, starget and s9 to demonstrate string substitution with insert(), replace() and append(). Finally swap() is used to swap two strings.

The max_size() function returns the maximum size of a string.

Note Don't do a find() and compare the result with -1. Always compare string::npos instead. Thsi code below is bad.

int result = s.find("text") ;
if (result == -1)
...
That is better.
if (result == string::npos)
...

Using Find

The four overloads of Find() do a case sensitive search a string for a match with a second string or char *. Download Example 6
const string s("Humpty Dumpty sat on a wall.") ;
string s2="on a ";
int DPos = s.find("Dumpty") ; // 7
int FPos = s.find('D') ; // 7
int EPos= s.find("sat",16) ; // npos

On the next page : More find functions and comparing strings

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. Learn C++ Programming
  6. Using String functions - An Example

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

All rights reserved.