给定两字符串S1和S2,若s1删除若干字符后能成为s2,则s1为s2的字串,找出s2在s1中起始位置最大值C++
时间: 2024-02-25 09:55:55 浏览: 83
字符串操作的源代码(拷贝,连接..)
以下是C++的实现代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int find_starting_position(string s1, string s2) {
int i = 0, j = 0, start = -1;
while (i < s1.length()) {
if (s1[i] == s2[j]) {
j += 1;
if (j == s2.length()) {
start = i - j + 1;
j = 0;
}
} else {
j = 0;
}
i += 1;
}
return start;
}
int main() {
string s1 = "hello world";
string s2 = "world";
int start = find_starting_position(s1, s2);
if (start == -1) {
cout << "s2 is not a substring of s1" << endl;
} else {
cout << "s2 starts at position " << start << " in s1" << endl;
}
return 0;
}
```
注意:这里的起始位置是从0开始计数的,如果返回-1表示s2不是s1的子串。
阅读全文