The value returned is just a pointer to a single character, at the position in str where the substring was found. What the user chooses to do with that information in a matter of personal preference.
In this case, at line 13, the contents of the string, starting from the position pointed to, will be displayed. Printing stops when the null character is reached at the end of the string.
|
cout << "Substring found: " << substr;
|
The function here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
// Return pointer to substring or null if not found.
char *get_substr(char *sub, char *str) {
int t;
char *p, *p2, *start;
for(t=0; str[t]; t++) {
p = &str[t]; // reset the pointers.
start = p;
p2 = sub;
while(*p2 && *p2==*p) { //check for substring.
p++;
p2++;
} /* If at end of p2 (i.e., substring), then a match has been found. */
if(!*p2) return start; // return pointer to beginning of substring
}
return 0; // no match found.
}
|
This code in several places depend upon the fact that a c-string must end with a zero byte, known as a null terminator.
for(t=0; str[t]; t++)
This for loop steps through the string one position at a time, and will halt when the condition
str[t]
is
false
, that is, the byte at position t is zero.
Within that loop is contained this loop:
1 2 3 4
|
while(*p2 && *p2==*p) { //check for substring.
p++;
p2++;
}
|
Here p2 is pointing to a character in the substring, and p is pointing to a character in the string being searched. It compares the corresponding characters and continues while both these conditions are true:
*p2
- that is, the current character in the substring is not zero
*p2==*p
- the characters are equal.
When that loop ends, it means either of those conditions might be true. So then there is a check, to see which one caused the loop to end. If the character pointed to by p2 is zero, then each character in the substring must have matched a character in the string, the search was successful, so the value of start (current position in the string is returned as the result.