-
pointer proggy
I need to write an implementation for search that steps through the string comparing each character wit the given character. If it finds a match, it will return a pointer to the current position. If it reaches the end of the string without finding a match, it will return a null pointer.
Can anyone help me do it?
Here is my code so far:#include <stdio.h>
char* search (char* s, int c) {
/*code here*/
}
int main () {
char quick_fox [] = "The quick brown fox jumps over the lazy dog.";
char c;
char* p;
c = 'x';
p = search(quick_fox, c);
if (p) {
printf("The substring that starts with %c is \"%s\"\n", c, p);
} else {
printf("No %c in \"%s\"\n", c, quick_fox);
}
c = 'X';
p = search(quick_fox, c);
if (p) {
printf("The substring that starts with %c is \"%s\"\n", c, p);
} else {
printf("No %c in \"%s\"\n", c, quick_fox);
}
}
-
what about the standard strchr function?
-
-
You need a temporary pointer that points to the beginning of the string. You can increment the temporary pointer (++) and get the character to where the temporary pointer is pointing by placing a * before it (it's called dereferencing). Just loop through the string and stop when you find a match or when you are at the end of the string. Here a beginning of the search function. You only have to fill in the while and if statement and you're done.
Code:
char* search (char* s, int c)
{
char *tmp = s;
if(tmp != NULL)
{
while( /* while not end of string and no match with c */ )
tmp++;
if( /* if at end of string then return NULL pointer */ )
tmp = NULL;
}
return tmp;
}
Here an example of dereferencing:
Code:
int main(void)
{
char s[] = "Hello world\n";
char *tmp = s;
while(*tmp != '\0') /* while not end of string */
{
printf("%c", *tmp); /* print character */
tmp++;
}
return 0;
}