String in C++
The string type supports variable-length character strings. The library takes care of managing the memory associated with storing the characters and provides various useful operations. The library string type is intended to be efficient enough for general use.
As with any library type, programs that use strings must first include the associated header. Our programs will be shorter if we also provide an appropriate using declaration:
Example
#include <iostream> using namespace std; // system namespace int main() { string s; // empty string cout <<"Enter a String "; cin >> s; // read whitespace-separated string into s cout << s << endl; // write s to the output getchar(); return 0; }
Ways to Initialize a string
string s1; | Default constructor; s1 is the empty string |
string s2(s1); | Initialize s2 as a copy of s1 |
string s3(“value”); | Initialize s3 as a copy of the string literal |
string s4(n, ‘c’); | Initialize s4 with n copies of the character ‘c’ |
string Operations
s.empty() | Returns true if s is empty; otherwise returns false |
s.size() | Returns number of characters in s |
s[n] | Returns the character at position n in s; positions start at 0. |
s1 + s2 | Returns a string equal to the concatenation of s1 and s2 |
s1 = s2 | Replaces characters in s1 by a copy of s2 |
v1 == v2 | Returns true if v1 and v2 are equal; false otherwise |
!=, <, <=, >, and >= | Have their normal meanings |
Example (calculates size of string)
#include <iostream> using namespace std; // system namespace int main() { string st("The expense of spirit\n"); cout << "The size of " << st << "is " << st.size() << " characters, including the newline" << endl; getchar(); return 0; }
Output
The size of The expense of spirit is 22 characters, including the newline