string pointer

Hey I am working on a problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Rewrite the following function so that it does not use any square brackets (not even in the parameter declarations) but does use the integer variable k.

    // This function searches through str for the character chr.
    // If the chr is found, it returns a pointer into str where
    // the character was first found, otherwise NULL (not found).

    const char* findTheChar(const char str[], char chr)
    {
        for (int k = 0; str[k] != 0; k++)
            if (str[k] == chr)
                return &str[k];

        return NULL;
    }


Does this mean I need to change the parameter type from const char to a string?
Last edited on
Not necessarily. Remember that if p is a pointer and i is an integer, p[i] is just a shorthand for *(p + i).
Last edited on
Does this mean I need to change the parameter type from const char to a string?


I suspect it means you need to write it without using subscripts.

1
2
3
4
const char* findTheChar(const char* str, char chr)
{
   // ...
}
Ok, thanks alot, so I think I got it by basically replacing str[k] with *(str + k).

However, Im having trouble with the next part which states:

Now rewrite the function shown in part b so that it uses neither square brackets nor any integer variables. Your new function must not use any local variables other than the parameters.

Would this work?
1
2
3
4
5
6
7
8
9
10
11
const char* findTheChar(const char* str, char chr)
    {
		while(*str != 0)
		{
                      if (*(str) == chr)
                           return &*(str);
		 	   str++;
		}

        return NULL;
    }
Last edited on
It can be written simpler

1
2
3
4
5
6
const char* findTheChar( const char* str, char chr )
{
	while( *str && *str != chr ) ++str;

	return ( *str ? str : 0 );
}

...or even simpler, return std::strchr(str, chr);
@Cubbi

...or even simpler, return std::strchr(str, chr);

Just my five cents

return strchr(str, chr);


:):)




Last edited on
Topic archived. No new replies allowed.