Namaran

Code daily. Without assist.

2026-08-22

starts_with.cpp

#include <string>

bool starts_with(const std::string& s, const std::string& prefix) {
    // write this: true if s starts with prefix
}

starts_withを実装してください。sprefixで始まっていればtrueを返します。(C++20のstd::string::starts_withは使わないこと。)

Reference
bool starts_with(const std::string& s, const std::string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

まず長さを比較し、prefixsより長ければ即座にfalseにできます。3引数版のcompareは、sの先頭prefix.size()文字とprefixを比較します。これは参考実装であり、唯一の正解ではありません — 自分の実装と比較してみてください。