从一个主串中查找子串第一次出现的位置

本文深入探讨了Sunday算法,这是一种在字符串搜索中效率较高的方法。通过对比其他算法,Sunday算法展现出其在特定场景下的优势。
在C++中,查找子串第一次出现位置有多种方法,以下为你详细介绍: ### 使用`std::string`的`find`方法 `std::string`类提供了`find`方法,用于查找子串整体首次出现的位置。若找到子串,会返回子串在字符中的起始索引;若未找到,则返回`std::string::npos`。 ```cpp #include <iostream> #include <string> int main() { std::string str1 = "ahedhello111"; std::string str2 = "hello"; size_t pos = str1.find(str2); if (pos != std::string::npos) { std::cout << "子串首次出现的位置: " << pos << std::endl; } else { std::cout << "未找到该子串。" << std::endl; } return 0; } ``` 此方法适用于使用`std::string`类型的字符,操作方便且直观[^2]。 ### 使用`std::string`的`find_first_of`方法 `find_first_of`方法用于查找子串中任意字符首次出现的位置。 ```cpp #include <iostream> #include <string> int main() { std::string str1 = "ahedhello111"; std::string str2 = "hello"; size_t pos = str1.find_first_of(str2); std::cout << "子串中任意字符首次出现的位置: " << pos << std::endl; return 0; } ``` 这里返回的是子串中任意字符首次出现的位置,并非子串整体首次出现的位置,使用时需注意区分[^2]。 ### 手动实现查找函数 手动编写代码实现查找子串首次出现位置的功能,可加深对算法的理解。 ```cpp #include <iostream> #include <cstring> int Find(const char s1[], const char s2[]) { int len1 = strlen(s1); int len2 = strlen(s2); for (int i = 0; i < len1; i++) { int j1 = i; int j2 = 0; while (s1[j1] == s2[j2]) { if (j2 == len2 - 1) return i; j1++; j2++; } } return -1; } int main() { char s1[100] = "ahedhello111"; char s2[100] = "hello"; int n = Find(s1, s2); if (n != -1) { std::cout << "子串首次出现的位置: " << n << std::endl; } else { std::cout << "未找到该子串。" << std::endl; } return 0; } ``` 手动实现能灵活处理各种情况,但代码相对复杂,需要考虑边界条件和算法效率[^4]。 ### 使用`strstr`函数(针对C风格字符) `strstr`函数是C标准库中的函数,用于在一个字符查找一个字符首次出现的位置。 ```cpp #include <iostream> #include <cstring> int main() { const char* s1 = "ahedhello111"; const char* s2 = "hello"; const char* result = std::strstr(s1, s2); if (result != nullptr) { int pos = result - s1; std::cout << "子串首次出现的位置: " << pos << std::endl; } else { std::cout << "未找到该子串。" << std::endl; } return 0; } ``` `strstr`函数返回的是指向子串首次出现位置的指针,通过指针相减可得到子串的起始索引[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值