So, the idea was a write a recursive function that compares two strings to see if string ‘prefix’ is contained in string ‘other’, without using any standard string functions, and using pointer arithmetic. below is what i came up with. i think it works, but was curious – how elegant is this, scale 1-10, any obvious funky moves you would have done instead?
thanks.
bool is_prefixR(char* prefix, char* other) {
static int prePos = 0,othPos = 0;
// static int othPos = 0;
bool test;
test = ( *(prefix+prePos) == *(other+othPos)); //checks to see if same
if (!*(prefix+prePos)) { return 1; } //end of recursion
if (!*(other+othPos)) { return 0; }
if (!test) {
othPos++; //move othPos pointer by 1
prePos = 0; //reset the prefix position
return(is_prefixR(prefix, other)); //lets try again
} else { //chars are the same
othPos++; //move othPos pointer by 1
prePos++;
return(is_prefixR(prefix, other)); //lets try again
}
return 0;
}
It is 1AM and far to late for understanding code, however such a simple function should be really easy to comprehend and your code isn’t. Static variables when writing functions are not a good idea because they make it incredibly hard to debug as the function ceases to become stateless. Try passing the values you need to the next function, and if you find you can’t, try writing it a different way. You also used prefix in the wrong way. I think you meant substring.
I present two functions below that do what you want and are fairly foolproof with everything except strings that are not null terminated. It is not quite as fast as it could be, as
is_substrwill continue to try and compare even whenotheris shorter thansub. You seemed to indicate elegance was the name of the game though, so I avoided all added complexity.Note:
is_substrdepends onis_prefix.Just to give you an idea of the functions output