// Program: string_matching2.C
// find the first occurrence of a string (provided as command
// line argument) within the input text, and output text so far
#include
int main (int argc, char* argv[])
{
if (argc < 2) {
// no command line arguments (except program name)
std::cout << "Usage: string_matching \n";
return 1;
}
// search string: second command line argument
char* s = argv[1];
// determine search string length m
unsigned int m = 0;
for (char* p = s; *p != '\0'; ++p) ++m;
// cyclic text window of size n
char* t = new char[m];
unsigned int w = 0; // number of characters read so far
unsigned int i = 0; // index where t logically starts
// find pattern in the text being read from std::cin
std::cin >> std::noskipws; // don't skip whitespaces!
for (unsigned int j = 0; j < m;)
// compare search string with window at j-th element
if (w < m || s[j] != t[(i+j)%m])
// input text still too short, or mismatch:
// advance window by replacing first character
if (std::cin >> t[i]) {
std::cout << t[i];
++w; // one more character read
j = 0; // restart with first characters
i = (i+1)%m; // of string and window
continue;
} else
// no more characters in the input
break;
else
// match: go to next character
++j;
std::cout << "\n";
delete[] t;
return 0;
}