gpt4 book ai didi

c++ - 找出字符串是否以 C++ 中的另一个字符串结尾

转载 作者:IT老高 更新时间:2023-10-28 11:25:32 26 4
gpt4 key购买 nike

在 C++ 中如何判断一个字符串是否以另一个字符串结尾?

最佳答案

使用 std::string::compare 简单地比较最后的 n 个字符:

#include <iostream>

bool hasEnding (std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}

int main () {
std::string test1 = "binary";
std::string test2 = "unary";
std::string test3 = "tertiary";
std::string test4 = "ry";
std::string ending = "nary";

std::cout << hasEnding (test1, ending) << std::endl;
std::cout << hasEnding (test2, ending) << std::endl;
std::cout << hasEnding (test3, ending) << std::endl;
std::cout << hasEnding (test4, ending) << std::endl;

return 0;
}

关于c++ - 找出字符串是否以 C++ 中的另一个字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/874134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com