LoginSignup
2

More than 1 year has passed since last update.

posted at

updated at

C++20便利機能の紹介:文字列チェック三銃士(2/3) starts_with, ends_with

C++20標準ライブラリの文字列クラスでは「先頭/末尾一致を確認するメンバ関数」が追加されます。

  • starts_with:対象は指定する部分文字列から始まっている?
  • ends_with:対象は指定する部分文字列で終わっている?

えー、いまさらーとか言わないソコ

starts_withとends_with

文字列クラスstd::stringと文字列ビュークラスstd::string_viewそれぞれに、starts_with, ends_withメンバ関数が追加されます。1

C++20
#include <string>
#include <string_view>

void download(std::string_view url)
{
  if (url.starts_with("http://") || url.starts_with("https://")) {
    // http(s)スキームを処理...
  } else {
    // ...
  }
}

void process_path(std::string path)
{
  // path末尾が / となるよう正規化
  if (!path.ends_with('/')) {
    path += '/';
  }
  // ...
}

※注意:前掲コードでは動作例示のためにstd::stringを使いましたが、ファイルパスに関する処理は std::filesystem::pathクラス の方が適しています。

Three string checking Musketeers

starts_withends_withは “Three string checking Musketeers(文字列チェック三銃士)2” のうちの2関数です。最後の1つ contains は、2023年に予定されているC++23標準ライブラリへの追加が決定しています。3

  • contains:対象は指定する部分文字列を含んでいる?

3人揃うまであと3年待ってね ☆(ゝω・)vキャピ

参考ページ


  1. 厳密には文字列クラステンプレートstd::baisc_string<E,T,A>と文字列ビュークラステンプレートstd::basic_string_view<E,T,A>に対して、それぞれ3種類のメンバ関数オーバーロード(文字列ビュー, 単一文字, NULL終端文字へのポインタ)が追加されます。 

  2. "Three string checking Musketeers" という表現は提案文書 P1679R3 より借用しました。このフレーズが気に入ったのでこの記事を書いただけともいう。 

  3. Trip report: Autumn ISO C++ standards meeting (virtual) – Sutter’s Mill 「I can already hear the chorus of "finally!"」 

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
2