bool repeat_char(char *s, int n);
//R: s is a C-string of at least n non-NUL characters and n > 0
//E: returns true if the first n characters are fully repeated throughout the string s, false
// otherwise.
I’m having trouble implementing this function using traversal by pointer. I was thinking that I could extract the first n characters from s, then use that in a comparison with s, but I’m not sure how I could do that. If I’m traversing through s one character at a time, how can I check that it matches a block of text, such as the first n characters of s?
Thanks!
You can really only compare the characters one at a time, so you start at
sands+n, and compare a character. If they match, you compare the character ats+1tos+n+1. If they matching, go tos+2, and so on up ton. If they match up to that point, repeat starting from s+n*2, then s+n*3, etc., until you reach the end of the string.If you find a mismatch, or reach the end of the string anywhere except matching the last character of the sub-string, then you return false. Otherwise, you return true.