查找一个字符串在另外一个字符串指定范围中首次和最后一次出现的位置
时间: 2024-04-29 10:26:30 浏览: 24
你好!感谢您的提问。针对您的问题,我可以提供以下代码:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "abcdefgdefhijk";
string str2 = "def";
int pos1 = 2;
int pos2 = 8;
cout << "String 1: " << str1 << endl;
cout << "String 2: " << str2 << endl;
cout << "Search from position " << pos1 << " to " << pos2 << endl;
int first = str1.find(str2, pos1);
int last = str1.rfind(str2, pos2);
if (first != string::npos && last != string::npos) {
cout << "First occurrence of " << str2 << " in string 1: " << first << endl;
cout << "Last occurrence of " << str2 << " in string 1: " << last << endl;
} else {
cout << "String 2 not found in specified range of string 1" << endl;
}
return 0;
}
```
上述代码中,我们使用 `find()` 函数和 `rfind()` 函数分别查找字符串 `str2` 在字符串 `str1` 中最先和最后一次出现的位置。指定范围可以通过 `pos1` 和 `pos2` 参数来实现。如果找到了字符串 `str2`,则输出它在字符串 `str1` 中的位置。如果未找到,则输出一个错误消息。