fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main(){
  7. string txt;
  8. string pttrn;
  9. int sizeP;
  10. int sizeT;
  11. //Se ingresa el patrón a buscar en el texto.
  12. getline(cin, pttrn);
  13. //getchar();
  14. getline(cin, txt);
  15.  
  16. //Se encuentra la longitud del patrón y del texto en el que se buscará.
  17. sizeT = txt.length();
  18. sizeP = pttrn.length();
  19.  
  20. //Si no hay ningún patrón, se retorna 0.
  21. if (sizeP == 0 || sizeT < sizeP){
  22. return 0;
  23. }
  24. //Aquí se recorre el texto en búsqueda de ocurrencias del patrón, saltando las posiciones del string
  25. //donde no puedan haber ocurrencias del patrón. En caso de que haya una ocurrencia, se imprime la
  26. //posición del texto en la que empieza la ocurrencia.
  27. for(int i = -1; i < (sizeT - sizeP); i++){
  28. int j = 0;
  29. if(pttrn[j] == txt[i + 1]){
  30. while(j < sizeP){
  31. if(pttrn[j] == txt[i + 1]){
  32. i += 1;
  33. j += 1;
  34. if(j + 1 == sizeP) cout << i - j + 1 << " ";
  35. } else break;
  36. }
  37. }
  38. }
  39. cout << endl;
  40. //system("PAUSE");
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 2860KB
stdin
foobarfoo
barfoobarfoobarfoobarfoobarfoo
stdout
3 15