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

在C++中判断两个字符串是否互为子串,核心是检查其中一个字符串是否包含在另一个字符串中。如果str1是str2的子串,或者str2是str1的子串,则它们“互为子串”关系成立(注意:严格意义上“互为子串”通常意味着彼此都能作为对方的子串,这种情况只在两字符串相等时成立;但一般理解为“至少一个是另一个的子串”)。
使用std::string的find方法
C++标准库中的std::string提供了find函数,可用于查找子串位置。若返回值不是std::string::npos,说明子串存在。
判断两个字符串是否有一个是另一个的子串:
#include#include bool isSubString(const std::string& a, const std::string& b) { return a.find(b) != std::string::npos || b.find(a) != std::string::npos; }
说明:
立即学习“C++免费学习笔记(深入)”;
- 如果b是a的子串,
a.find(b)会返回起始索引(非npos)。 - 如果a是b的子串,
b.find(a)也会成功。 - 只要其中一个成立,就返回true。
处理“严格互为子串”的情况
若要求“互为子串”表示每个都是对方的子串,那么只有当两个字符串完全相等时才满足条件(因为短字符串不可能包含长字符串)。
bool areMutualSubStrings(const std::string& a, const std::string& b) {
return a == b;
}
注意:这种情况下,长度不同则不可能互为子串。
完整示例代码
#include#include 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方法简洁高效,适合大多数场景。注意空字符串的情况:空串是任何字符串的子串,可根据需求决定是否特殊处理。











