请问在一个父字符串 s 中是否存在子字符串 t 。如果存在,则输出子字符串 t 在父字符串中所有的起始位置,如果不存在,则输出 -1
。
比如:假设父字符串 s=Go Abc good goole
,子字符串 t=go
,那么输出位置:
8
13
输入
第一行输入父字符串的值(字符串长度不超过 100 )。
第二行输入子字符串的值(子字符串长度不超过 100 )。
输出
输出子字符串在父字符串中所有的位置,如果父字符串中不存在子字符串,请输出 -1
。
样例
输入
复制
Go Abc good goole! go
输出
复制
8 13
输入
复制
Go Abc good goole! Good
输出
复制
-1
#include <iostream>
#include <string>
using namespace std;
void findSubstringPositions(const string& s, const string& t) {
size_t pos = s.find(t);
if (pos == string::npos) {
cout << -1 << endl;
} else {
while (pos!= string::npos) {
if(t.size()>=2)
cout << pos+t.size()-1 <<endl;
pos = s.find(t, pos + 1);
}
cout << endl;
}
}
int main() {
string s, t;
getline(cin, s);
getline(cin, t);
findSubstringPositions(s, t);
return 0;
}