British0zzy
July 22nd, 2008, 11:45 PM
I have only just learned about pointers in C and as practice I am writing a function which finds the rightmost occurrence of the string t in a string s.
The program I wrote to test the function prints the input, and only prints the output if the function returns a positive integer.
Here are my test input and output:
oula //input
oula //output: incorrect
1 //output
oulb //input
oulb //output: incorrect
1
could
could //output: correct
2
coulb
coulb //output: incorrect
2
ould ould
ould ould //output: correct
6
ould could o
ould could o //output: incorrect
8
ould could ou
ould could ou //output: correct
7
ould could oul
ould could oul //output: incorrect
9
ould could ould
ould could ould //output: correct
12
Here is the function so far:
/* strrindex: returns the position of the rightmost
occurance of t in s, or -1 if there is none. */
int strrindex(char *s, char *t)
{
int i = 0;
char *p = t; /* p is a temporary pointer to preserve t and s */
while (*(s+i)) /* find end of s */
i++;
while (*p) { /* find first space available for t */
p++;
i--;
}
for (p = (s+i); i >= 0; p = (s + (--i))) { /* check each position of s for t */
while (*(p++) == *(t++) && *t != '\0')
;
if (*t == '\0')
return i + 1;
}
return -1;
}
Do you have any suggestions to attacking this problem? Am I doing it right or is there a much easier way?
Thanks.
The program I wrote to test the function prints the input, and only prints the output if the function returns a positive integer.
Here are my test input and output:
oula //input
oula //output: incorrect
1 //output
oulb //input
oulb //output: incorrect
1
could
could //output: correct
2
coulb
coulb //output: incorrect
2
ould ould
ould ould //output: correct
6
ould could o
ould could o //output: incorrect
8
ould could ou
ould could ou //output: correct
7
ould could oul
ould could oul //output: incorrect
9
ould could ould
ould could ould //output: correct
12
Here is the function so far:
/* strrindex: returns the position of the rightmost
occurance of t in s, or -1 if there is none. */
int strrindex(char *s, char *t)
{
int i = 0;
char *p = t; /* p is a temporary pointer to preserve t and s */
while (*(s+i)) /* find end of s */
i++;
while (*p) { /* find first space available for t */
p++;
i--;
}
for (p = (s+i); i >= 0; p = (s + (--i))) { /* check each position of s for t */
while (*(p++) == *(t++) && *t != '\0')
;
if (*t == '\0')
return i + 1;
}
return -1;
}
Do you have any suggestions to attacking this problem? Am I doing it right or is there a much easier way?
Thanks.