Because after I compile, instead of telling me where the specific character is located, it gives me the string starting with that character instead. I thought that it should return *str instead. However, it gives me an error doing that.
But that doesn't have any impact on what the code actually does. Which is find a character that matches and returns a pointer to it.
I suspect the problem is how you're dealing with the return value.
For instance:
1 2
char* s = "xbacxefx" ;
char * a = pStrChr(s, 'a') ;
a is a pointer and holds the memory location where 'a' first appears in s. You seem to be expecting it to return the character found. Why would it do that? You already know what that character is. What you need to know is where that character is, and that is exactly what you get.
Maybe an illustration would be better. The following finds and replaces 'x' in the string pointed to by s using your implementation of pStrChr.
1 2 3 4 5 6 7 8 9 10 11 12
char s[] = "xbacxefx";
std::cout << s << '\n' ;
char* x = pStrChr(s, 'x');
while (*x)
{
*x= 'o' ;
x = pStrChr(x, 'x') ;
}
std::cout << s << '\n' ;}
char* pStrChr( char* str, int character )
{
while( *str )
{
if ( *str == character )
{
break;
}
*str++;
}
return str;
}
through the compiler, it returns the balance of the string, not the position of the character. For example, if str = "abcd" and character = 'c' it returns "cd" not 3 like it's supposed to.
through the compiler, it returns the balance of the string, not the position of the character. For example, if str = "abcd" and character = 'c' it returns "cd" not 3 like it's supposed to.
No, it returns the address of the character found. The address of the character 'c' in the quote is the same as the address of "cd".
#include <iostream>
#include <cstddef>
char* pStrChr( char* str, int character )
{
while( *str )
{
if ( *str == character )
{
break;
}
str++;
}
return str;
}
int main()
{
char s[] = "this is some text.";
std::cout << "s as a c string: " << s << '\n' ;
std::cout << "It's address is " << int(&s[0]) << '\n' ;
char * tPos = pStrChr(s, 't') ;
while ( *tPos )
{
std::cout << "found a 't' !\n" ;
std::cout << "The location of the t is " << (int)tPos << '\n' ;
std::cout << "Derefencing the pointer = " << *tPos << '\n' ;
std::ptrdiff_t dist = tPos - &s[0] ;
std::cout << "Distance from s = " << dist << '\n' ;
// notice any relation between dist and the index into s of
// the character we found?
tPos = pStrChr(tPos+1, 't') ;
}
}