HOWTO · C++
如何在 C++ 中从字符串获取最后一个字符
本文讨论从 C++ 中的字符串中获取最后一个字符。
本页内容
对于 "Spider Man" 这样的字符串,text.back() 直接引用其最后一个字符。当您想要经过检查的位置访问时,也可以使用 at(text.size() - 1)。在使用这些方法中的任何一种之前,字符串必须包含一个字符。
在 C++ 中使用 std::string::at 从字符串中获取最后一个字符
std::string::at(index) 返回从零开始的位置处的字符,并检查该位置是否在字符串内。最后一个位置是 text.size() - 1。如果索引在字符串之外,at() 会抛出 std::out_of_range;索引类型是无符号的,因此负值会转换为一个较大的无符号值,而不是作为有效的负索引。
运行此示例:
#include <iostream>
#include <string>
int main() {
const std::string text = "Spider Man";
std::cout << "Character at position 3: " << text.at(3) << '\n';
std::cout << "Character at last position: "
<< text.at(text.size() - 1) << '\n';
}
第一次访问使用索引 3;第二次根据字符串长度计算最后一个索引。在计算和使用该最后位置之前,请检查字符串不为空。
在 C++ 中使用 std::string::back() 从字符串中获取最后一个字符
std::string::back() 是访问最后一个字符的直接方式。它返回一个引用,因此您可以通过该引用读取字符或赋予替换值。在空字符串上调用 back() 是未定义行为,因此在使用前请检查字符串。
#include <iostream>
#include <string>
int main() {
std::string text = "Spider Man";
const char last = text.back();
std::cout << "Character at the end: " << last << '\n';
text.back() = '@';
std::cout << "After replacement: " << text << '\n';
}
第一次调用读取 n;赋值将字符串更改为 "Spider Ma@"。
在 C++ 中使用 std::string::rbegin() 从字符串中获取最后一个字符
std::string::rbegin() 返回一个反向迭代器,其第一个位置对应于字符串的最后一个字符。只要字符串不为空,解引用它即可读取该字符。
#include <iostream>
#include <string>
int main() {
const std::string text = "Spider Man";
const auto last = *text.rbegin();
std::cout << "The last character is: " << last << '\n';
}
在进行反向迭代时使用 rbegin();对于单个字符,back() 更直接。
在 C++ 中使用 std::reverse 和字符串迭代器获取最后一个字符
std::reverse 是在 <algorithm> 中声明的算法,而不是 std::string 成员函数。它就地反转迭代器范围内的元素。反转非空字符串后,text.front() 引用原来位于最后的字符。这会更改整个字符串,因此当您只需要读取其最后一个字符时,通常没有必要这样做。
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text = "Spider Man";
std::reverse(text.begin(), text.end());
std::cout << "The former last character is: " << text.front() << '\n';
}
该算法在从 begin() 到 end() 的半开区间上运行。在之后读取 front() 之前,请确保字符串不为空。
在 C++ 中使用 std::string::substr() 从字符串中获取最后一个字符
std::string::substr(position, count) 返回一个新字符串。对于至少包含一个字符的字符串,text.substr(text.size() - 1, 1) 将其最后一个字符提取为一个单字符字符串。在计算起始位置之前,请检查是否存在字符。
#include <iostream>
#include <string>
int main() {
const std::string text = "Spider Man";
const std::string last = text.substr(text.size() - 1, 1);
std::cout << "Last character extracted: " << last << '\n';
}
当结果应该是字符串时选择 substr();当 char 足够时使用字符访问操作。
在 C++ 中使用数组索引访问字符串的字符
std::string 支持 operator[],因此在确认字符串不为空后,最后一个字符可以读取为 text[text.size() - 1]。与 at() 不同,operator[] 对于超出范围的位置不提供相同的经过检查的访问。
#include <iostream>
#include <string>
int main() {
const std::string text = "Spider Man";
std::cout << "The last character is: "
<< text[text.size() - 1] << '\n';
}
索引从零开始:对于长度为 n 的字符串,最后一个字符位于索引 n - 1 处。如果您希望通过异常报告超出范围的索引,请优先使用 at()。
结论
要直接访问非空 std::string 的最后一个字符,请使用 back()。当经过检查的位置访问有用时,选择 at(size() - 1)。rbegin() 也通过反向迭代到达最后一个字符,substr() 将其作为字符串返回,而索引使用相同的最后位置,但没有 at() 的边界检查。在访问字符串末尾之前,请检查字符串包含一个字符。