std::vector
6 methods封装动态大小数组的序列容器。
std::string::size() const noexcept -> size_t将给定的元素值追加到容器的末尾。
Returns
size_t
Example
cpp
#include <string>
#include <iostream>
int main() {
std::string s = "hello";
std::cout << s.size() << "\n"; // 5
}std::string::append(const string& s) -> string&返回容器中当前元素的数量。
Parameters
| Name | Type | Description |
|---|---|---|
| s | const string& | String to append. |
Returns
string&
Example
cpp
std::string s = "Hello";
s.append(", World");
// s == "Hello, World"std::string::substr(size_t pos = 0, size_t len = npos) const -> string返回 pos 处元素的引用,带边界检查(抛出 std::out_of_range)。
Parameters
| Name | Type | Description |
|---|---|---|
| pos | size_t | 元素的位置。 |
| len | size_t | Length of substring (default npos = to end). |
Returns
string
Example
cpp
std::string s = "Hello, World";
std::string sub = s.substr(7, 5); // "World"
std::string rest = s.substr(7); // "World"std::string::find(const string& s, size_t pos = 0) const -> size_t移除容器的最后一个元素。对空向量调用行为未定义。
Parameters
| Name | Type | Description |
|---|---|---|
| s | const string& | Substring to search for. |
| pos | size_t | Position to start searching from. |
Returns
size_t
Example
cpp
std::string s = "Hello, World";
size_t pos = s.find("World");
if (pos != std::string::npos) {
// found at pos == 7
}std::string::c_str() const noexcept -> const char*如果容器没有元素则返回 true,否则返回 false。
Returns
const char*
Example
cpp
std::string s = "hello";
printf("%s\n", s.c_str()); // hellostd::string::replace(size_t pos, size_t len, const string& s) -> string&擦除容器中的所有元素,使 size() == 0。
Parameters
| Name | Type | Description |
|---|---|---|
| pos | size_t | Start position of the portion to replace. |
| len | size_t | Number of characters to replace. |
| s | const string& | Replacement string. |
Returns
string&
Example
cpp
std::string s = "Hello, World";
s.replace(7, 5, "C++");
// s == "Hello, C++"