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

starts_with and ends_with on strings

Use case

Check string prefixes/suffixes.

Explanation

Before C++20: s.find("_OBJC_") == 0 or s.substr(0, 6) == "_OBJC_. Now just s.starts_with("_OBJC_).

Code

#include <iostream>
#include <string>
#include <string_view>

void classifySymbol(std::string_view sym) {
  if (sym.starts_with("_OBJC_")) {
    std::cout << sym << ": ObjC metadata.\n";
  } else if (sym.starts_with("_Z")) {
    std::cout << sym << ": C++ mangled.\n";
  } else if (sym.ends_with("_block_invoke")) {
    std::cout << sym << ": ObjC block.\n";
  } else {
    std::cout << sym << ": Other.\n";
  }
}

int main() {
  // https://stackoverflow.com/questions/12323417/symbol-not-found-objc-class-nsobject
  classifySymbol("_OBJC_CLASS_$_NSObject");
  // https://en.wikipedia.org/wiki/Name_mangling
  classifySymbol("_ZN9org8wikipedia7Article6formatEv");
  // https://apple-dev.groups.io/g/xcode/topic/symbolic_breakpoints_some/34200828
  classifySymbol(
      "-[UIPresentationController runTransitionForCurrentState]_block_invoke");
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/starts_with-ends_with
_OBJC_CLASS_$_NSObject: ObjC metadata.
_ZN9org8wikipedia7Article6formatEv: C++ mangled.
-[UIPresentationController runTransitionForCurrentState]_block_invoke: ObjC block.