There are multiple ways and useful functions to determine whether a substring or a character is part of another string. Historically, the standard
C++ functions provide this feature through proxies that do not directly reflect the intent of the code:
- The
find
functions on std::string
and std::string_view
return an index into the searched string. The
substring or character is not present when the index is equal to npos
(often spelled -1
).
- The
std::strstr
and std::strchr
functions (inherited from C) return a pointer into the searched string. When they
return nullptr
, the substring or character is not present.
While these functions work, they complexify the code:
- They do not work at the right abstraction level. Instead of just returning a
bool
indicating whether the substring is present,
they return a proxy from which the information can be decoded. This requires some boilerplate code that clouds the indent of the code.
- Their names do not reflect the performed task. The names of the C functions are arguably hard to read and obscure. They only make sense after
reading their documentation. Furthermore,
find
also has a name unrelated to the current task.
Thankfully, C++23 introduces contains
on std::string
and std::string_view
to simplify this task.
This rule raises an issue when it detects code that could be improved with the use of contains
.