C++ Template Library Module25 Tenouk
C++ Template Library Module25 Tenouk
Note:
Program examples in this Module compiled using Visual C++ 6.0 with SP6 and Visual C++ .Net. g++ (GNU C++
run on my Fedora 3 machine) example is given at the end of this Module. Take note also for the codes that span
more than one line, which they are not supposed to.
Abilities
25.1 Introduction
- Before we ‘jump’ into the real STL ‘bandwagon’, let try the <string> C++ Standard Library. This
library is constructed using template classes and functions.
- In this Module take note for these words: container, iterator and algorithm. See how these things
used in the program examples.
- We will discuss these ‘creatures’ in more detail later on. May be after completing this Module, you
may develop your own simple search routine :o) program.
- Your main task here is ‘learn how to use’.
- <string> defines the container template class basic_string and various supporting templates.
You must include the <string> header in your program as shown below.
#include <string>
Type Description
string
A type that describes a specialization of the
typedef basic_string<char>
string; template class basic_string with elements
e.g. of type char as a string. This means
const basic_string <char> basic_string<char> is synonym to
str1("TEST"); string.
or
string str2("TEST");
wstring
A type that describes a specialization of the
typedef template class basic_string with elements
basic_string<wchar_t> of type wchar_t as a wstring. This means
wstring; basic_string<wchar_t> is synonym to
e.g. wstring. This is wide char, normally 2 byte
const basic_string <wchar_t> such as Unicode character set (more information
str1(L"EST"); on this is discussed HERE and the
or implementation is HERE).
wstring str2(L"EST");
www.tenouk.com Page 1 of 38
Table 25.1 string and wstring typedefs
int main( )
{
const basic_string <char> str1("TEST");
//Uses the typedef for string word
//synonym to basic_string <char>
string str2("TEST");
Output:
▪ It finds two corresponding characters unequal, and the result of their comparison is taken as the
result of the comparison between the strings.
▪ It finds no inequalities, but one string has more characters than the other, and the shorter string is
considered less than the longer string.
▪ It finds no inequalities and finds that the strings have the same number of characters, and so the
strings are equal.
www.tenouk.com Page 2 of 38
Operator Brief Description
operator!= Tests if the string object on the left side of the operator is not equal
str1 != str2 to the string object on the right side.
operator== Tests if the string object on the left side of the operator is equal to
str1 == str2 the string object on the right side.
operator< Tests if the string object on the left side of the operator is less than
str1 < str2 to the string object on the right side.
operator<<
same as in iostream, e.g. A template function that inserts a string into the output stream.
cout<<
operator<= Tests if the string object on the left side of the operator is less than
str1 <= str2 or equal to the string object on the right side.
operator> Tests if the string object on the left side of the operator is greater
str1 > str2 than to the string object on the right side.
operator>= Tests if the string object on the left side of the operator is greater
str1 >= str2 than or equal to the string object on the right side.
operator>>
same as in iostream, e.g. A template function that extracts a string from the input stream.
cin>>
operator+
string str13 = str1 + Concatenates two string objects.
str3
int main( )
{
//Declaring an objects of type basic_string<char>
string str1("testingone");
string str2("testingtwo");
cout<<"str1 string is = "<<str1<<endl;
cout<<"str2 string is = "<<str2<<endl;
//Declaring a C-style string
char *str3 = "testingone";
cout<<"C-style str3 string is = "<<str3<<endl;
www.tenouk.com Page 3 of 38
cout<<"str1 & str2 are not equal."<<endl;
Output:
int main()
{
//Declaring objects of type basic_string<char>
string str1("testingthree");
string str2("testingtwo");
cout<<"str1 is = "<<str1<<endl;
cout<<"str2 is = "<<str2<<endl;
www.tenouk.com Page 4 of 38
else
cout<<"str3 is not less then string str2."<<endl;
Output:
int main( )
{
//Declaring an objects of type basic_string<char>
string str1("testingone");
string str2("testingtwo");
cout<<"str1 string is = "<<str1<<endl;
cout<<"str2 string is = "<<str2<<endl;
//Declaring a C-style string
www.tenouk.com Page 5 of 38
char *str3 = "testingone";
cout<<"str3 C-style string is = "<<str3<<endl;
Output:
www.tenouk.com Page 6 of 38
- The operator skips the leading white spaces unless the skipws flag is set. It reads all the following
characters until the next character is a white space or the end of the file is reached.
int main()
{
string Sample = "Testing the << and >> operators.";
string Var1, Var2;
cout<<Sample<<endl;
cout<<"Enter a string or a word: ";
cin>>Var1;
cout<<"Enter another string or a word: ";
cin>>Var2;
cout<<"The strings entered are: "<<Var1<<" and "<<Var2<<endl;
return 0;
}
Output:
int main()
{
//Declaring an object of type basic_string<char>
string str1("StringOne");
string str2("StringTwo");
//Declaring a C-style string
char *str3 = "StringThree";
//Declaring a character constant
char chr = '?';
www.tenouk.com Page 7 of 38
cout<<"str2 string is = "<<str2<<endl;
cout<<"str3 C-style string is = "<<str3<<endl;
cout<<"A character constant chr is = "<<chr<<endl;
Output:
Specialized Template
Description
Function
swap() Exchanges the arrays of characters
of two strings.
- If the strings being swapped have the same allocator object, the swap() member function:
- Otherwise, it performs a number of element assignments and constructor calls proportional to the
number of elements in the two controlled sequences.
//swap()
#include <string>
#include <iostream>
using namespace std;
int main()
{
//Declaring an object of type basic_string<char>
string str1("StringOne");
string str2("StringTwo");
www.tenouk.com Page 8 of 38
cout<<"Before swapping string str1 and str2:"<<endl;
cout<<"str1 string is = "<<str1<<endl;
cout<<"str2 string is = "<<str2<<endl;
swap(str1, str2);
cout<<"\nOperation: swap(str1, str2)"<<endl;
cout<<"After swapping string str1 and str2:"<<endl;
cout<<"str1 string is = "<<str1<<endl;
cout<<"str2 string is = "<<str2<<endl;
return 0;
}
Output:
Function Description
The getline() function creates a string containing all of the
characters from the input stream until one of the following
situations occurs:
getline()
- End of file.
- The delimiter is encountered.
- is.max_str elements have been extracted.
- Program example
//getline()
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str;
string str1;
string str2;
cout<<"Enter a line of text: ";
getline(cin, str);
cout<<"You entered: "<<str<<endl;
cout<<"Enter a line of text, <space> as the delimiter: "<<endl;
getline(cin, str1, ' ');
cout<<"You entered: "<<str1<<endl;
return 0;
}
Output:
www.tenouk.com Page 9 of 38
- With <string>, we are provided with two string template classes as shown in the following table.
Class Description
A template class that describes objects that can store a sequence
basic_string
of arbitrary character-like objects.
A template class that describes attributes associated with a
char_traits
character of type CharType
- The sequences controlled by an object of template class basic_string are the Standard C++ string
class and are usually referred to as strings, but they should not be confused with the null-terminated C-
strings used throughout the Standard C++ Library.
- The string class is a container that enables the use of strings as normal types, such as using
comparison and concatenation operations, iterators and STL algorithms. The basic_string
template structure is shown below.
template <
class CharType,
class Traits = char_traits<CharType>,
class Allocator = allocator<CharType>
>
- Where:
Entity Description
The data type of a single character to be stored in the string. The Standard C++
CharType Library provides two specializations of this template class:
1. string, for elements of type char,
2. wstring, for elements of type wchar_t.
Traits Various important properties of the CharType elements in a basic_string
specialization are described by the class Traits.
The type that represents the stored allocator object that encapsulates details about
Allocator
the string's allocation and de-allocation of memory. The default value is
allocator<Type>.
- The following table is the list of the typedef used in basic_string template class. Their usages are
presented in the program examples part.
www.tenouk.com Page 10 of 38
A type that provides a random-access iterator that can read any const
const_reverse_iterator element in the string. A type const_reverse_iterator cannot
modify the value of a character and is used to iterate through a string in
reverse.
A type that provides the difference between two iterators those refer to
elements within the same string. The signed integer type describes an
difference_type object that can represent the difference between the addresses of any
two elements in the controlled sequence. For type string, it is
equivalent to ptrdiff_t.
A type that provides a random-access iterator that can read or modify
any element in a string. A type iterator can be used to modify the
iterator
value of a character and is used to iterate through a string in a forward
direction.
An unsigned integral value initialized to –1 that indicates either "not
found" or "all remaining characters" when a search function fails.
npos When the return value is to be checked for the npos value, it might not
work unless the return value is of type size_type and not either int
or unsigned.
A type that provides a pointer to a character element in a string or
character array. The type is a synonym for
pointer
allocator_type::pointer. For type string, it is equivalent
to char*.
A type that provides a reference to an element stored in a string. A type
reference can be used to modify the value of an element.
reference
The type is a synonym for allocator_type::reference.
For type string, it is equivalent to chr&.
A type that provides a random-access iterator that can read or modify an
element in a reversed string. A type reverse_iterator can be
reverse_iterator
used to modify the value of a character and is used to iterate through a
string in reverse.
An unsigned integral type for the number of elements in a string. It is
size_type equivalent to allocator_type::size_type. For type string,
it is equivalent to size_t.
A type for the character traits of the elements stored in a string. The
traits_type type is a synonym for the second template parameter Traits.
For type string, it is equivalent to char_traits<char>.
A type that represents the type of characters stored in a string. It is
value_type equivalent to traits_type::char_type and is equivalent to
char for objects of type string.
- The following table is a list of member functions available in basic_string template class.
www.tenouk.com Page 11 of 38
position in a source string to a target character array.
data() Converts the contents of a string into an array of characters.
empty() Tests whether the string contains characters or not.
end()
Returns an iterator that addresses the location succeeding the last
element in a string.
Removes an element or a range of elements in a string from
erase()
specified positions. Notice the different with clear().
find()
Searches a string in a forward direction for the first occurrence of
a substring that matches a specified sequence of characters.
find_first_not_of()
Searches through a string for the first character that is not any
element of a specified string.
find_first_of()
Searches through a string for the first character that matches any
element of a specified string.
find_last_not_of()
Searches through a string for the last character that is not any
element of a specified string.
find_last_of()
Searches through a string for the last character that is an element
of a specified string.
get_allocator() Returns a copy of the allocator object used to construct the string.
insert()
Inserts an element or a number of elements or a range of elements
into the string at a specified position.
length() Returns the current number of elements in a string.
max_size() Returns the maximum number of characters a string could contain.
push_back() Adds an element to the end of the string.
rbegin() Returns an iterator to the first element in a reversed string.
rend()
Returns an iterator that point just beyond the last element in a
reversed string.
Replaces elements in a string at a specified position with specified
replace() characters or characters copied from other ranges or strings or C-
strings.
reserve()
Sets the capacity of the string to a number at least as great as a
specified number.
resize()
Specifies a new size for a string, appending or erasing elements as
required.
rfind()
Searches a string in a backward direction for the first occurrence
of a substring that matches a specified sequence of characters.
size() Returns the current number of elements in a string.
substr()
Copies a substring of at most some number of characters from a
string beginning from a specified position.
swap() Exchange the contents of two strings.
- The following table is a list of the operators available in basic_string template class.
- Let try program examples demonstrating the basic_string template class member functions and
other creatures readily available for us.
www.tenouk.com Page 12 of 38
append()
- Characters may be appended to a string using the operator+= or the member functions append()
or push_back().
- operator+= appends single-argument values while the multiple-argument append() member
function allows a specific part of a string to be specified for adding.
//append()
#include <string>
#include <iostream>
using namespace std;
int main()
{
//appending a C-string to a string
string str1("Playing ");
const char *str2 = "with a string";
Output:
www.tenouk.com Page 13 of 38
assign()
- The strings can be assigned new character values. The new value can be either a string and C-string or
a single character.
- The operator= may be used if the new value can be described by a single parameter; otherwise the
member function assign(), which has multiple parameters, can be used to specify which part of the
string is to be assigned to a target string.
int main()
{
//assigning the characters of a C-string to a string
string str1;
const char *str2 = "StRiNg assign()";
www.tenouk.com Page 14 of 38
cout<<"Newly assigned str5 string is: "<<str5<<endl;
Output:
at()
- The first element of the string has an index of zero and the following elements are indexed
consecutively by the positive integers, so that a string of length n has an nth element indexed by the
number n – 1.
www.tenouk.com Page 15 of 38
- The member operator[] is faster than the member function at() for providing read and write
access to the elements of a string.
- The member operator[] does not check whether the index passed as a parameter is valid but the
member function at() does and so should be used in the validity is not certain. An invalid index,
which is an index less that zero or greater than or equal to the size of the string, passed to the member
function at() throws an out_of_range class exception.
- An invalid index passed to the operator[] results in undefined behavior, but the index equal to the
length of the string is a valid index for const strings and the operator returns the null-character when
passed this index.
- The reference returned may be invalidated by string reallocations or modifications for the non-const
strings.
//at()
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1("Operation"), str2("Desert Storm");
const string constr1("Making cakes"), constr2("Start eating");
cout<<"---constr1.length()---"<<endl;
cout<<"The length of the constr1 string is: "<<unsigned int(constr1.length())<<endl;
cout<<"\n---constr2.at(8)---"<<endl;
cout<<"The 8th character of the constr2 is: "<<cRefStr2<<endl;
return 0;
}
Output:
www.tenouk.com Page 16 of 38
basic_string::basic_string
- Constructs a string that is empty or initialized by specific characters or that is a copy of all or part of
some other string object or C-string.
- The five member functions and their parameters are shown below but it is not our concern here. We
just want to know how to use the member functions in our program.
- Then, the following program example tries to describe the string object initialization.
basic_string(
const value_type* _Ptr,
size_type _Count = npos,
const allocator_type& _Al = Allocator()
);
basic_string(
const basic_string& _Right,
size_type _Roff = 0,
size_type _Count = npos
);
basic_string(
const basic_string& _Right,
size_type _Roff = 0,
size_type _Count = npos,
const allocator_type& _Al = Allocator()
);
basic_string(
size_type _Count,
value_type _Ch,
const allocator_type& _Al = Allocator()
);
explicit basic_string(
const allocator_type& _Al = Allocator()
);
template <class InputIterator>
basic_string(
InputIterator _First,
InputIterator _Last,
const allocator_type& _Al = Allocator()
);
- The constructors for class basic_string create and initialize strings as follows:
▪ The first member function creates a string that is initialized by all or part of a C-string.
▪ The second member function creates a string that is initialized by all or part of an object of type
basic_string.
▪ The third member function creates a string that is initialized by a specific number of characters of
a parameter stipulated value.
▪ The fourth member function creates an empty string.
▪ The fifth member function creates a string that is initialized by the characters in the range whose
boundaries are delimited by input iterators.
www.tenouk.com Page 17 of 38
//basic_string
#include <string>
#include <iostream>
using namespace std;
int main()
{
//initializing with a C-string
const char *str1 = "The basic_string";
basic_string <char> str2(str1, 5);
cout<<"str1 string is: "<<str1<<endl;
cout<<"Operation: str2(str1, 5)"<<endl;
cout<<"str2 initialized by str1 is: "<<str2<<"\n\n";
Output:
www.tenouk.com Page 18 of 38
begin()
- If the return value of begin() is assigned to a const_iterator, the string object cannot be
modified.
- If the return value of begin() is assigned to an iterator, the string object can be modified.
//begin(), end()
#include <string>
#include <iostream>
using namespace std;
int main()
{
www.tenouk.com Page 19 of 38
}
Output:
c_str()
- Objects of type string belonging to the C++ template class basic_string<char> are not
necessarily null terminated.
- The null character ' \0 ' is used as a special character in a C-string to mark the end of the string but has
not special meaning in an object of type string and may be a part of the string just like any other
character.
- There is an automatic conversion from const char* into strings, but the string class does not
provide for automatic conversions from C-style strings to objects of type basic_string<char>.
- The returned C-style string should not be modified, as this could invalidate the pointer to the string, or
deleted, as the string has a limited lifetime and is owned by the class string.
int main( )
{
Output:
www.tenouk.com Page 20 of 38
capacity()
- The member function capacity() returns the storage currently allocated to hold the controlled
sequence, a value at least as large as size.
int main( )
{
string str1("Testing the capacity()");
cout<<"str1 string is: "<<str1<<endl;
SizeStr1 = str1.size();
LenStr1 = str1.length();
CapStr1 = str1.capacity();
MaxSizeStr1 = str1.max_size();
Output:
www.tenouk.com Page 21 of 38
clear()
- The string on which the member function clear() is called will be empty.
//clear()
#include <string>
#include <iostream>
using namespace std;
int main( )
{
//str1.clear();
cout<<"\nErasing part of the string using erase(13)"<<endl;
str1.erase(13);
cout<<"Operation: str1.erase(13)"<<endl;
cout<<"The modified str1 string is: ";
//using iterator...
for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)
cout<<*StrIter;
cout<<endl;
www.tenouk.com Page 22 of 38
return 0;
}
Output:
compare()
- The compare() member functions compare either all or part of the parameter and operand strings
depending on which in used.
- A negative return value if the operand string is less than the parameter string; zero if the two strings are
equal; or a positive value if the operand string is greater than the parameter string.
int main()
{
www.tenouk.com Page 23 of 38
cout<<"The last 5 characters of the str6 string is greater than\n"
<<"the str7 string."<<endl;
cout<<endl;
Output:
int main()
{
//comparing part of a string to part of a string
int str8;
string str9("TestFourth");
string str10("TFourthT");
cout<<"str9 string is: "<<str9<<endl;
cout<<"str10 string is: "<<str10<<endl;
str11 = str12.compare(str13);
cout<<"Operation: str12.compare(str13)"<<endl;
if(str11 < 0)
cout<<"The str12 string is less than the str13 C-string."<<endl;
else if(str11 == 0)
www.tenouk.com Page 24 of 38
cout<<"The str12 string is equal to the str13 C-string."<<endl;
else
cout<<"The str12 string is greater than the str13 C-string."<<endl;
cout << endl;
Output:
copy()
www.tenouk.com Page 25 of 38
- A null character is not appended to the end of the copy.
- The return value is the number of characters actually copied.
//copy()
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1("Testing the copy()");
basic_string <char>::iterator StrIter;
//declare and initialize arrays to 0
char Array1[20] = {0};
char Array2[10] = {0};
basic_string <char>:: pointer Array1Ptr = Array1;
basic_string <char>:: value_type *Array2Ptr = Array2;
Output:
data()
- Objects of type string belonging to the C++ template class basic_string <char> are not
necessarily null terminated.
- The return type for data() is not a valid C-string, because no null character gets appended. The null
character '\0 ' is used as a special character in a C-string to mark the end of the string, but has no
special meaning in an object of type string and may be a part of the string object just like any other
character.
- There is an automatic conversion from const char* into strings, but the string class does not
provide for automatic conversions from C-style strings to objects of type basic_string <char>.
- The returned string should not be modified, because this could invalidate the pointer to the string, or
deleted, because the string has a limited lifetime and is owned by the class string.
- The return value is a pointer to the first element of the array containing the contents of the string, or, for
an empty array, a non-null pointer that cannot be dereferenced.
www.tenouk.com Page 26 of 38
int main()
{
string str1("Testing the data()");
cout<<"str1 string object is: "<<str1<<endl;
cout<<"Operation: str1.length()"<<endl;
cout<<"The length of str1 = "<<unsigned int(str1.length())<<"\n\n";
Output:
empty()
- The return value is true if the string object contains no characters; false if it has at least one character.
- The empty() is equivalent to size == 0.
//empty()
#include <string>
#include <iostream>
using namespace std;
int main()
{
bool Var1, Var2;
string str1("Testing the empty()");
cout<<"str1 string object is: "<<str1<<endl;
Var1 = str1.empty();
//test the emptiness
cout<<"Operation: str1.empty()"<<endl;
if(Var1)
cout<<"str1 string object is empty."<<endl;
else
cout<<"str1 string object is not empty."<<"\n\n";
www.tenouk.com Page 27 of 38
cout<<"str3 string object is not empty."<<endl;
return 0;
}
Output:
end()
- The return value is a random-access iterator that addresses the location succeeding the last element in a
string.
- end() is often used to test whether an iterator has reached the end of its string. The value returned by
end() should not be dereferenced.
- If the return value of end() is assigned to a const_iterator, the string object cannot be
modified. If the return value of end() is assigned to an iterator, the string object can be modified.
//begin(), end()
#include <string>
#include <iostream>
using namespace std;
int main( )
{
string str1("Testing the end()");
basic_string <char>::iterator StrIter, Str1Iter;
Str1Iter = str1.end();
//minus the null character, so point to the real
//last character in the string...
Str1Iter--;
cout<<"Operation: str1.end() then Str1Iter--"<<endl;
cout<<"str1 string is: "<<str1<<endl;
cout<<"The last character of the str1 string is: "<<*Str1Iter<<endl;
//end() used to test when an iterator has reached the end of its string
cout<<"Using forward iterator the str1 is: ";
for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)
cout<<*StrIter;
cout<<"\n\n";
Output:
www.tenouk.com Page 28 of 38
erase()
- The return value: For the first two member functions, an iterator addressing the first character after the
last character removed by the member function.
- For the third member function, a reference to the string object from which the elements have been
erased.
- The third member function returns *this.
//erase()
#include <string>
#include <iostream>
using namespace std;
int main()
{
//using a range...
string str1("Testing the erase() part I");
basic_string <char>::iterator Str1Iter;
cout<<"str1 string object is: "<< str1<<endl;
Output:
find()
- The return value is the index of the first character of the substring searched for when successful;
otherwise npos.
www.tenouk.com Page 29 of 38
//find() part I
#include <string>
#include <iostream>
using namespace std;
int main()
{
//don't forget the null character
//searching for a single character in a string
string str1("Search part I, a character in a string");
cout<<"str1 string is: "<<str1<<endl;
basic_string <char>::size_type index1, index2;
static const basic_string <char>::size_type npos = -1;
index2 = str1.find('t');
cout<<"Operation: str1.find('t')"<<endl;
if(index2 != npos)
cout<<"The index of the 't' found in str1 is: "<<unsigned int(index2)<<endl;
else
cout<<"The character 't' was not found in str1."<<endl;
cout<<endl;
//---------------------------------------------------------------------
//searching a string for a substring as specified by a C-string
string str2("Search part II, a substring in string");
cout<<"str2 string is: "<<str2<<endl;
basic_string <char>::size_type index3, index4;
Output:
www.tenouk.com Page 30 of 38
//find() part II
#include <string>
#include <iostream>
using namespace std;
int main()
{
//don't forget the null character
//searching a string for a substring as specified by a C-string
static const basic_string <char>::size_type npos = -1;
string str3("Again, search part III");
cout<<"str3 string is: "<<str3<<endl;
basic_string <char>::size_type index5, index6;
//--------------------------------------------------------------
//searching a string for a substring as specified by a string
string str4("Finally!, search part IV");
cout<<"str4 string is: "<<str4<<endl;
basic_string <char>::size_type index7, index8;
string str5("part");
index7 = str4.find(str5, 4);
cout<<"Operation: str4.find(str5, 4)"<<endl;
if(index7 != npos)
cout<<"The index of the 1st element of 'part' "
<<"after\nthe 4th position in str4 is: "<<unsigned int(index7)<<endl;
else
cout<<"The substring 'part' was not found in str4"<<endl;
cout<<endl;
string str6("arch");
index8 = str4.find(str6);
cout<<"Operation: str4.find(str6)"<<endl;
if(index8 != npos)
cout<<"The index of the 1st element of 'arch' in "
<<"str4 is: "<<unsigned int(index8)<<endl;
else
cout<<"The substring 'arch' was not found in str4"<<endl;
return 0;
www.tenouk.com Page 31 of 38
}
Output:
find_first_not_of()
- The return value is the index of the first character of the substring searched for when successful;
otherwise npos.
//find_first_not_of() part I
#include <string>
#include <iostream>
using namespace std;
int main()
{
//searching a single character in a string
string str1("Testing the find_first_not_of() part 1");
cout<<"str1 string is: "<<str1<<endl;
basic_string <char>::size_type index1, index2;
static const basic_string <char>::size_type npos = -1;
index2 = str1.find_first_not_of('T');
cout<<"\nOperation: str1.find_first_not_of('T')"<<endl;
if(index2 != npos)
cout<<"The index of the 'non T' found in str1 is: "<<unsigned int(index2)<<endl;
else
cout<<"The character 'non T' was not found in str1."<<endl;
cout<<endl;
//---------------------------------------------------------------------------
//searching a string for a substring as specified by a C-string
string str2("Testing the find_first_not_of() part 2");
cout<<"str2 string is: "<<str2<<endl;
basic_string <char>::size_type index3, index4;
const char *cstr2 = "df";
www.tenouk.com Page 32 of 38
cout<<"The index of the 1st element of 'gz' after\nthe 0th position in str2 is: "
<<unsigned int(index4)<<endl;
else
cout<<"The substring 'gz' was not found in str2"<<endl;
return 0;
}
Output:
//find_first_not_of() part II
#include <string>
#include <iostream>
using namespace std;
int main()
{
//searching a string for a substring as specified by a C-string
string str3("Testing the find_first_not_of() part 3");
cout<<"str3 string is: "<<str3<<endl;
basic_string <char>::size_type index5, index6;
static const basic_string <char>::size_type npos = -1;
//--------------------------------------------------------------------
//searching a string for a substring as specified by a string
string str4("Testing the find_first_not_of() part 4");
cout<<"str4 string is: "<<str4<<endl;
basic_string <char>::size_type index7, index8;
string str5("tf7");
index7 = str4.find_first_not_of(str5, 3);
cout<<"Operation: str4.find_first_not_of(str5, 3)"<<endl;
if(index7 != npos)
www.tenouk.com Page 33 of 38
cout<<"The index of the 1st non occurrence of an element\nof 'tf7' "
<<"in str4 after the 3rd position is: "<<unsigned int(index7)<<endl;
else
cout<<"Elements other than those in the substring 'tf7' "
<<"were not found in the string str4."<<endl;
string str6("in");
index8 = str4.find_first_not_of(str6);
cout<<"\nOperation: str4.find_first_not_of(str6)"<<endl;
if(index8 != npos)
cout<<"The index of the 1st occurrence of an "
<<"element of\n'in' in str4 after the 0th "
<<"position is: "<<unsigned int(index8)<<endl;
else
cout<<"Elements other than those in the substring"
<<" 'in' were not found in the string str4."<<endl;
return 0;
}
Output:
find_first_of()
- The return value is the index of the first character of the substring searched for when successful;
otherwise npos.
//find_first_of() part I
#include <string>
#include <iostream>
using namespace std;
int main( )
{
//searching for a single character in a string
string str1("find_first_of()");
cout<<"str1 string is: "<<str1<<endl;
basic_string <char>::size_type index1, index2;
static const basic_string <char>::size_type npos = -1;
index2 = str1.find_first_of('z');
cout<<"\nOperation: str1.find_first_of('z')"<<endl;
if(index2 != npos)
cout<<"The index of the 'z' found in str1 is: "<<unsigned int(index2)<<endl;
else
cout<<"The character 'z' was not found in str1."<<endl;
www.tenouk.com Page 34 of 38
//--------------------------------------------------------
//searching a string for a substring as specified by a C-string
string str2("Testing 123...Testing 123");
cout<<"\nstr2 string is: "<<str2<<endl;
basic_string <char>::size_type index3, index4;
Output:
//find_first_of() part II
#include <string>
#include <iostream>
using namespace std;
int main( )
{
//searching a string for a substring as specified by a C-string
string str3("Testing 456...Testing 456...789");
cout<<"str3 string is: "<<str3<<endl;
basic_string <char>::size_type index5, index6;
static const basic_string <char>::size_type npos = -1;
www.tenouk.com Page 35 of 38
cout<<"\nOperation: str3.find_first_of(cstr3, index5 + 1, 2)"<<endl;
if(index6 != npos)
cout<<"The index of the second occurrence of an"
<<"element\nof 't68' in str3 after the 0th "
<<"position is: "<<unsigned int(index6)<<endl;
else
cout<<"Elements of the substring 't68' were not\n"
<<"found in str3 after the first occurrence."<<endl;
cout<<endl;
//------------------------------------------------------------
//searching a string for a substring as specified by a string
string str4("find_first_of() and find_first_of()");
cout<<"str4 string is: "<<str4<<endl;
basic_string <char>::size_type index7, index8;
string str5("dfz");
index7 = str5.find_first_of(str5, 3);
cout<<"Operation: str5.find_first_of(str5, 3)"<<endl;
if(index7 != npos)
cout<<"The index of the 1st occurrence of an "
<<"element\nof 'dfz' in str4 after the 3rd "
<<"position is: "<<unsigned int(index7)<<endl;
else
cout<<"Elements of the substring 'dfz' were not\n"
<<"found in str4 after the 3rd position."<<endl;
string str6("fo");
index8 = str4.find_first_of(str6);
cout<<"\nOperation: str4.find_first_of(str6)"<<endl;
if(index8 != npos)
cout<<"The index of the 1st occurrence of an "
<<"element\nof 'fo' in str4 after the 0th "
<<"position is: "<<unsigned int(index8)<<endl;
else
cout<<"Elements of the substring 'fo' were not\n"
<<"found in str4 after the 0th position."<<endl;
return 0;
}
Output:
//**********string.cpp**************
//append()
#include <string>
#include <iostream>
using namespace std;
int main()
{
//appending a C-string to a string
www.tenouk.com Page 36 of 38
string str1("Playing ");
const char *str2 = "with a string";
www.tenouk.com Page 37 of 38
Operation: str7 += str9
The re appended string is: First Second Third
------------------------------To be continued-------------------------------
---www.tenouk.com---
www.tenouk.com Page 38 of 38