top1编程
← 返回题目
题解

【入门】求子串的位置

1 条题解

  • 0
    @ 2026-7-28 23:24:50
    #include <bits/stdc++.h>
    using namespace std;
    int main() {
    	string s,t;
    	getline(cin,s);
    	getline(cin,t);
    	int p=s.find(t);//查找第一次是否出现
    	if(p==-1){//没出现
    		cout<<-1;
    	}else{
    		while(p!=-1){//还能找到
    			cout<<p+1<<endl;//输出当前出现下标
    			p=s.find(t,p+1);//更新查找位置
    			//p+1:从上一个出现的下一个位置开始查找
    		}
    	}
    	return 0;
    }
    
    • 1