1.4.4 Searching a String
Like other languages, C++ allows us to search a string for a value, however the syntax is a little different compared to languages like Java.
Find Command
In C++, you use the find
command to search a string. If the string is found, the position where the first instance is found is returned.
When the string is not found, the string no position value is returned. This value is represented as string::npos
.
Here is an example of the syntax to search for a cat
.
Assigning a Value While Evaluating
One of the more unique features of C++ is that you can assign a value in the same statement that you evaluate it. This allows you to combine statements in a logical way. For example, if you wanted to find whether a phrase contained cat
and print the position only if it does, you can do something like this:
Notice that the variable was declared before the conditional statement and the variable assignment is in parenthesis so that it is created before evaluating.
Try This Example
Last updated