Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::string::contains

Use case

Check if string contains substring.

Explanation

containt() returns bool directly. Cleaner than find() != npos.

Code

#include <print>
#include <string>

int main() {
  std::string symbol = "_OBJC_CLASS_$_NSObject";

  // Before C++23:
  // if (symbol.find("OBJC") != std::string::npos) {}

  // C++23:
  if (symbol.contains("OBJC")) {
    std::println("Objective-C symbol.");
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/std-string-contains
Objective-C symbol.