[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: vector Up: Strings Previous: Size

Routines

These string-specific routines (only a selection is shown below) provide the functionality that C people are used to. The names aren't too hard to remember, and the default arguments are reasonable. The routines are overloaded, so find can be used to look for strings, characters or even C-strings.

Note also that the c_str routine returns a C string.

   const charT* c_str() const;
   size_type find(const basic_string&,
                  size_type = 0) const;
   size_type find(charT, size_type = 0) const;
   size_type rfind(const basic_string&,
                   size_type = npos) const;
   size_type rfind(charT, size_type = npos) const;
   size_type find_first_of(const basic_string&,
                           size_type = 0) const;
   size_type find_last_of(const basic_string&,
                          size_type = npos) const;
   size_type find_first_not_of(const basic_string&,
                               size_type = 0) const;
   size_type find_last_not_of(const basic_string&,
                              size_type = npos) const;
   basic_string substr(size_type = 0, size_type = npos) const;
   int compare(const basic_string&) const;
   int compare(size_type, size_type, const basic_string&) const;

The case history (section 21) has many examples of string usage. Here are 2 short programs -

[fontsize=\small,frame=single,formatcom=\color{progcolor}]
#include <iostream>
#include <string>
using namespace std;

int main()
{
 string s1= "pine";
 string s2= "apple";
 cout << "length of s1 is " << s1.length() << endl;
 string s3= s1+s2;
 cout << "s1 + s2 = " << s3 << endl;
 string s4= s3.substr(2,4);
 cout << "s3.substr(2,4)=" << s4 << endl;
 
 cout << "s3.find(\"neap\")=" << s3.find("neap") << endl;
 cout << "s3.rfind('p')=" << s3.rfind('p') << endl; 
 return 0;
}

To get a line of text (that may include spaces) from the user, do

[fontsize=\small,frame=single,formatcom=\color{progcolor}]
#include <iostream>
#include <string>
using namespace std;

int main()
{
 string str;
 cout <<"Type a string ";
 getline(cin,str);
 cout <<"you typed " << str << endl;
 return 0;
}



Tim Love
2001-07-05