School-Coding-Cpp/sfusi/strstr().cpp

56 lines
967 B
C++

/*
Nome: Mario
Cognome: Montanari
strstr()
*/
#include <iostream>
#include <cstring>
#define SIZE 100+1
using namespace std;
char *strstr(const char *src1, const char *src2);
int main(void) {
char src1[SIZE] = "Ciao a tutti, come state?";
char src2[SIZE] = "tutti";
char *result;
cout << "Stringa iniziale: " << src1 << endl;
cout << "Sottostringa da trovare: " << src2 << endl;
result = strstr(src1, src2);
if (result != nullptr) {
cout << endl << "Sottostringa trovata: " << result << endl;
} else {
cout << endl << "Sottostringa non trovata." << endl;
}
return 0;
}
char *strstr(const char *src1, const char *src2) {
if (!*src2) return (char*)src1;
while (*src1) {
const char *ptr1 = src1;
const char *ptr2 = src2;
while (*ptr1 && *ptr2 && *ptr1 == *ptr2) {
ptr1++;
ptr2++;
}
if (!*ptr2) {
return (char*)src1;
}
src1++;
}
return nullptr;
}