C++ String Built-in Functions
1. Capacity Functions
| Function | Description |
|---|
s.size() | Returns the size (length) of the string. |
s.max_size() | Returns the maximum size a string can hold. |
s.capacity() | Returns the current capacity of the string. |
s.clear() | Removes all characters from the string. |
s.empty() | Returns true if the string is empty, otherwise false. |
s.resize(n) | Changes the size of the string to n. |
2. Element Access Functions
| Function | Description |
|---|
s[i] | Accesses the character at index i. |
s.at(i) | Accesses the character at index i with bounds checking. |
s.front() | Returns the first character of the string. |
s.back() | Returns the last character of the string. |
3. Modifier Functions
| Function | Description |
|---|
s += str | Appends another string to the current string. |
s.append(str) | Appends another string. |
s.push_back(ch) | Adds a character at the end of the string. |
s.pop_back() | Removes the last character of the string. |
s = str | Assigns a new string. |
s.assign(str) | Assigns a new string. |
s.erase(pos, len) | Removes characters from the string. |
s.replace(pos, len, str) | Replaces a portion of the string. |
s.insert(pos, str) | Inserts a string at a specific position. |
4. Iterator Functions
| Function | Description |
|---|
s.begin() | Returns an iterator pointing to the first character. |
s.end() | Returns an iterator pointing to the position after the last character. |
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << s.size() << endl;
cout << s.front() << endl;
cout << s.back() << endl;
s.push_back('!');
cout << s << endl;
s.pop_back();
cout << s << endl;
return 0;
}