Skip to content

Instantly share code, notes, and snippets.

@cyclotimia
Created September 30, 2015 11:11
Show Gist options
  • Save cyclotimia/cd9d7056b8fb7b520805 to your computer and use it in GitHub Desktop.
Save cyclotimia/cd9d7056b8fb7b520805 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
unsigned strlen(const char *str) {
const char *start = str;
while ('\0' != *str) {
++str;
}
int l = str - start;
return l;
}
int strstr(const char *text, const char *pattern) {
const char *text1 = text; // копируем text в переменную
const char *pattern1 = pattern; // копируем pattern в переменную
// cout << *text << " " << text << endl;
// cout << *pattern << " " << pattern << endl;
int textlength = strlen(text); // длина text
int patternlength = strlen(pattern); // длина pattern
int position = 0; // указатель на начало паттерна в тексте
if (patternlength == 0) {
// cout << "position=" << position;
return position;
}
if (patternlength > textlength){
return -1;
}
while ('\0' != *text) {
// cout << "*text=" << *text << " " << "text=" << text << endl;
if (*text == *pattern) {
position = textlength - strlen(text);
// cout << "position=" << position << endl;
text++;
pattern++;
if ('\0' == *pattern) {
position = 1+position - patternlength;
// cout << "end of pattern found, position=" << position << endl;
return position;
}
}
else {
text++;
position = -1;
pattern = pattern1;
// cout << pattern << endl;
}
}
// cout << position << endl;
return position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment