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

标签 c++ string ends-with

在 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/

相关文章:

java - 将字母数字字符串转换为数字 - NumberFormatException

r - 有没有一种方法可以 dplyr (tidyverse) 映射我的数据集,找到以相同后缀结尾的列,然后只保留一个?

c++ - std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' ) 使用#include <Windows.h> 时出错

c++ - 克利昂 2016.3 : switch to "Release" configuration

javascript - 匹配字符串中模式的出现并在 javascript 中插入字符?

python - 如果以特定字符串结尾,则创建一个新列

javascript - 如何在纯 JavaScript 中以最快的方式检查字符串的最后一个字符是否是数字/数字?

c++ - c++中的表达式和表达式语句是什么?

c++ - 使用 C++ 解析文本文件(其中包含 HTML)

Java - 提取特殊字符和单词之间的文本