答案是使用find方法判断:若str1.find(str2) != npos 或 str2.find(str1) != npos,则一个字符串是另一个的子串;严格互为子串仅当两字符串相等。

在C++中判断两个字符串是否互为子串,核心是检查其中一个字符串是否包含在另一个字符串中。如果str1是str2的子串,或者str2是str1的子串,则它们“互为子串”关系成立(注意:严格意义上“互为子串”通常意味着彼此都能作为对方的子串,这种情况只在两字符串相等时成立;但一般理解为“至少一个是另一个的子串”)。
C++标准库中的std::string提供了find函数,可用于查找子串位置。若返回值不是std::string::npos,说明子串存在。
判断两个字符串是否有一个是另一个的子串:
#include <string>
#include <iostream>
bool isSubString(const std::string& a, const std::string& b) {
return a.find(b) != std::string::npos || b.find(a) != std::string::npos;
}
说明:
立即学习“C++免费学习笔记(深入)”;
a.find(b)会返回起始索引(非npos)。b.find(a)也会成功。若要求“互为子串”表示每个都是对方的子串,那么只有当两个字符串完全相等时才满足条件(因为短字符串不可能包含长字符串)。
bool areMutualSubStrings(const std::string& a, const std::string& b) {
return a == b;
}
注意:这种情况下,长度不同则不可能互为子串。
#include <string>
#include <iostream>
bool isOneSubStringOfOther(const std::string& a, const std::string& b) {
return a.find(b) != std::string::npos || b.find(a) != std::string::npos;
}
int main() {
std::string s1 = "hello";
std::string s2 = "ell";
if (isOneSubStringOfOther(s1, s2)) {
std::cout << "Yes, one is a substring of the other.\n";
} else {
std::cout << "No, neither is a substring.\n";
}
return 0;
}
输出结果为:Yes, one is a substring of the other.
基本上就这些。使用find方法简洁高效,适合大多数场景。注意空字符串的情况:空串是任何字符串的子串,可根据需求决定是否特殊处理。
以上就是c++++中如何判断两个字符串是否互为子串_c++字符串互为子串判断方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号