Reputation: 63
in my journey of learning c++ I have crossed into an interesting situation that I could not figure any way of fixing it
I tried creating a string type with a pointer sign on it (after adding the "using std::string ;")
But when trying to find something inside it after I already entered a value inside It gives me an error of must be a class type
Example:
string *something = new string("Something stringy - std::string");
inside that sting I tried searching for the substring "str"
While trying using this command:
cout << "The first occurrence of the substring 'str' in something starts at index " << *something.rfind("str", std::distance(begin(*something), end(*something))) << endl << endl << endl;
What is the correct way of doing so?
Upvotes: 0
Views: 496
Reputation: 1144
There are a few problems here.
The first is operator precedence. Consider the code *something.rfind("str")
. The .
operator has higher precedence than the *
operator, so this code is equivalent to *(something.rfind("str"))
, but we can't call a member function on a pointer directly. We can fix this by surrounding the dereference with parentheses to force it to happen first, or, more directly, by using the ->
operator, i.e. something->rfind("str")
.
The second problem is that rfind
searches from the end of the string, so it will find the last occurrence of the substring you are looking for, not the first. If you want to find the first occurrence use find
. Here's some documentation on std::string
that explains the different variants of find
.
The final problem is that the second argument to find
is the position at which to start searching. As written the starting position will be equal to the length of the string, so there will be nothing to search. Instead, to just start searching from the front of the string use the default value of 0.
The final solution:
cout << "The first occurrence of the substring 'str' in something starts at index "
<< something -> find("str")
<< endl
<< endl
<< endl;
Upvotes: 0
Reputation: 138211
The dot operator has precedence over the dereference operator: what you're trying to do amounts to *(something.rfind(...))
. Since something
has a pointer type instead of a class type, it has no dot operator, and you get an error.
You can either use (*something).rfind
or something->rfind
, the latter being shorter and more common. The ->
operator is the equivalent of the .
operator for pointers.
Upvotes: 6