/**
PPP18 ex#2:  Write a function,
char* findx(const char* s, const char* x),
that finds the first occurrence
of the C-style string x in s. Do not use any standard
library functions. Do not use subscripting;
use the dereference operator * instead.
*/

#include <iostream>
#include <string.h>
using namespace std;

char* findx(const char* s, const char* x) {

    int i = 0, j = 0;
    while(*(s+i)) { /// while not at the end of s
        while(*(x+j)) {
            if(!*(s+i+j)) return 0; ///got to the end of s without finishing x
            if(*(s+i+j) != *(x+j)) break; /// no match yet
            if(!*(x+j+1)) return const_cast<char*>(x); /// found it!
            ++j; /// look at next characters
        }
        ++i; /// go to next character in s
    }
}

char* getc_string() {
    size_t currentSize = 10;

   // Always make space for the terminating null character.
   char* words = new char[currentSize+1];
   size_t count = 0;

   char c;
   while(cin.get(c) && c!=char(10))
   {
      if ( count == currentSize )
      {
         // Allocate memory to hold more data.
         size_t newSize = currentSize*2;
         char* temp = new char[newSize+1];

         // Copy the contents from the old location to the new location.
         for ( size_t i = 0; i < currentSize; ++i )
         {
            temp[i] = words[i];
         }

         // Delete the old memory.
         delete [] words;

         // Use the new memory
         words = temp;
         currentSize = newSize;
      }

      words[count] = c;
      count++;
   }

   // Terminate the string with a null character.
   words[count] = '\0';

   return words;

   // The memory is automatically deallocated.
   // delete [] words;
}

int main() {
    /** /**
    string s;
    cout << "\nEnter string for s: ";
    getline(cin, s);
    string x;
    cout << "\nEnter string for x: ";
    getline(cin, x);
    char* s;
    char* x;*/
    cout << "\nEnter string for s: ";
    char* s = getc_string();
    cout << "\ngot " << s;
    cout << "\nEnter string for x: ";
    char* x = getc_string();
    if(findx(&s[0],&x[0]))
        cout << "\nFound " << x << " in " << s;
    else cout << "\nThe string " << x << " not found in " << s;
}

/**

Enter string for s: utter doggerel

Enter string for x: dog

Found dog in utter doggerel
Process returned 0 (0x0)   execution time : 17.165 s
*/
