在C++中,从字符串中提取后4个字符可以通过多种方式实现。以下是几种常见的方法:
substr
方法#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int len = str.length();
if (len >= 4) {
std::string lastFour = str.substr(len - 4);
std::cout << "Last 4 characters: " << lastFour << std::endl;
} else {
std::cout << "String is too short to extract 4 characters." << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int len = str.length();
std::string lastFour = "";
if (len >= 4) {
for (int i = len - 4; i < len; ++i) {
lastFour += str[i];
}
std::cout << "Last 4 characters: " << lastFour << std::endl;
} else {
std::cout << "String is too short to extract 4 characters." << std::endl;
}
return 0;
}
rbegin
和rend
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int len = str.length();
std::string lastFour = "";
if (len >= 4) {
for (auto it = str.rbegin(); it != str.rbegin() + 4; ++it) {
lastFour = *it + lastFour;
}
std::cout << "Last 4 characters: " << lastFour << std::endl;
} else {
std::cout << "String is too short to extract 4 characters." << std::endl;
}
return 0;
}
substr
方法:这是最简单的方法,直接使用substr
方法从字符串末尾提取指定长度的子字符串。rbegin
和rend
:使用反向迭代器从字符串末尾开始提取字符,适用于需要反向遍历字符串的场景。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云