Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
24 Strings and Streams<br />
char type is the type of the characters in the string. size type is a type used for indexing in the<br />
string. npos (“no position”) indicates a position beyond the end of the string; it may be returned<br />
by functions that search for characters in a string. Since size type is unsigned, npos represents<br />
positive infinity.<br />
1.2 Operations on Strings<br />
We now show some of the most important operations on strings (actually basic string’s). The<br />
operations are both member functions and global helper functions. We start with the member<br />
functions (for formatting reasons, some parameters of type size type have been specified as<br />
int):<br />
class string {<br />
public:<br />
/*** construction ***/<br />
string(); // create an empty string<br />
string(const string& s); // create a copy of s<br />
string(const char* cs); // create a string with the characters from cs<br />
string(const string& s, int start, int n); // create a string with n<br />
// characters from s, starting at position start<br />
string(int n, char ch); // create a string with n copies of ch<br />
}<br />
/*** information ***/<br />
int size(); // number of characters in the string<br />
int capacity(); // the string can hold this many characters<br />
// before resizing is necessary<br />
void reserve(int n); // set the capacity to n, resize if necessary<br />
/*** character access ***/<br />
const char& operator[](size_type pos) const;<br />
char& operator[](size_type pos);<br />
/*** substrings */<br />
string substr(size_type start, int n); // the substring starting at<br />
// position start, containing n characters<br />
/*** finding things ***/<br />
// see below<br />
/*** inserting, replacing, and removing ***/<br />
void insert(size_type pos, const string& s); // insert s at position pos<br />
void append(const string& s); // append s at the end<br />
void replace(size_type start, int n, const string& s); // replace n<br />
// characters starting at pos with s<br />
void erase(size_type start = 0, int n = npos); // remove n characters<br />
// starting at pos<br />
/*** assignment and concatenation ***/<br />
string& operator=(const string& s);<br />
string& operator=(const char* cs);<br />
string& operator=(char ch);<br />
string& operator+=(const string& s); // also for const char* and char<br />
/*** access to C-string representation ***/<br />
const char* c_str();<br />
• Note that there is no constructor string(char). Use string(1, char) instead.