三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

查找字符串代码分享

查找字符串代码分享

include

include

using namespace std;

int SubStrNum(const string &str, const string &substr) {
// 边界处理:子串为空或主串为空时,返回0
if (str.empty() || substr.empty()) {
return 0;
}

int count = 0;
size_t pos = 0; // 用于记录查找的起始位置
size_t len_sub = substr.size();

// 从pos位置开始查找子串,找到返回位置,找不到返回string::npos
while ((pos = str.find(substr, pos)) != string::npos) {
count++;
pos += len_sub; // 移动到匹配位置的下一个位置,避免重叠匹配
}

return count;
}

// 测试示例
int main() {
string s1 = "abcabcababc";
string s2 = "abc";
cout << SubStrNum(s1, s2) << endl; // 输出:3
return 0;
}

← 返回列表