The string class
#include <string> // different than <cstring> which is C's string.h
-
stringis the C++ class name for strings - C++ strings are much higher-level than C's, spares you the nitty gritty
- (C strings are still around and you occasionally need them, e.g. for
argv) - Still, they are not references: more like a
structthan a pointer to astruct - Different constructors to make new
stringobjects: invoke with function notation, nonewkeyword
std::string s1("hello"); // s1 is "hello"
std::string s2(3, 'x'); // s2 is "xxx"
std::string s3 = " world"; // calls copy constructor to make fresh copy of "world"
std::string s4; // empty string "" (NOT a null variable!)
// implicitly calls default constructor
std::string s5(s2); // calls copy constructor
String conversions
- no constructor for int or char conversions
- can assign character to string:
s1 = 'h';
String representation & operations
-
stringobject is not a pointer to a char array like in C -
s[5]still can be used to get individual characters froms, no range checking -
s.at(5)to get individual characters with range checking
s = "wow" // for assignment of literals
cin >> s // input from stream - stops at whitespace!
cout << s // output to stream
getline(is, s) // read to end of line from stream is, store in s
s1 = s2 // deep copy assignment
// or s1.assign(s2) s1.assign(s2, start, howmany)
s1 + s2 // string concatenation
s1 += s2 // same as s1 = s1 + s2, also same as s1.append(s2)
== != < > <= >= // relational operators overloaded, they just work (no strcmp needed)
s1.size() == s1.length() == number of characters
s1.capacity() // how many characters currently allocated (can increase, see reserve below)
s1.max_size() // max for all strings
s1.empty() // returns a bool
s1.reserve(s1.length() + 5); //changes capacity
s1.substr(where, howmany);
s1.compare(s2); // like C's strcmp; most of the time use overloaded < > etc instead
s1.c_str(); // get c-style string (null terminated character array)
Passing strings to functions
- Parameter type often best as a reference type in function header
void slurpit(string &s) - Otherwise you are passing a copy of the string, can be slow