Skip to content

C++ <string> API

C++ std::vector —— 一个连续的、可动态调整大小的数组,支持 O(1) 随机访问。

1 class · 6 methods

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

NameTypeDescription
sconst 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

NameTypeDescription
possize_t元素的位置。
lensize_tLength 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

NameTypeDescription
sconst string&Substring to search for.
possize_tPosition 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());  // hello
std::string::replace(size_t pos, size_t len, const string& s) -> string&

擦除容器中的所有元素,使 size() == 0。

Parameters

NameTypeDescription
possize_tStart position of the portion to replace.
lensize_tNumber of characters to replace.
sconst string&Replacement string.

Returns

string&

Example

cpp
std::string s = "Hello, World";
s.replace(7, 5, "C++");
// s == "Hello, C++"