将字符串的最后n个字符与C中的另一个字符串进行比较可以通过以下步骤实现:
以下是一个示例代码片段,演示如何在C++中实现这个功能:
#include <iostream>
#include <string>
bool compareLastNCharacters(std::string str, std::string c, int n) {
std::string lastNCharacters = str.substr(str.length() - n);
return lastNCharacters == c;
}
int main() {
std::string str = "Hello World";
std::string c = "World";
int n = 5;
bool result = compareLastNCharacters(str, c, n);
if (result) {
std::cout << "The last " << n << " characters match with " << c << std::endl;
} else {
std::cout << "The last " << n << " characters do not match with " << c << std::endl;
}
return 0;
}
这段代码将字符串"Hello World"的最后5个字符与字符串"World"进行比较。如果它们匹配,则输出"The last 5 characters match with World";否则,输出"The last 5 characters do not match with World"。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云