C++ std::basic_string::ends_with 関数徹底解説

2024-04-02

C++のストリングクラス std::basic_string::ends_with 関数

std::basic_string::ends_with 関数は、指定された文字列がストリングの末尾に一致するかどうかを検証します。一致する場合は true、一致しない場合は false を返します。

構文

bool ends_with(const basic_string_view& sv) const noexcept;
bool ends_with(const CharT* s) const noexcept;

パラメータ

  • sv: 一致させる文字列を表す std::basic_string_view オブジェクト
  • s: 一致させる文字列を表す null 終端文字列

戻り値

  • 文字列が sv または s で終わる場合は true、それ以外は false

詳細

  • ends_with 関数は、大文字と小文字を区別します
  • 部分一致ではなく、完全一致のみを検出します。
  • 空の文字列は、どのような文字列とも一致しません。
  • sv または s が空の場合、ends_withfalse を返します。

#include <iostream>
#include <string>

int main() {
  std::string str = "Hello, world!";

  // "world!" で終わるか確認
  if (str.ends_with("world!")) {
    std::cout << "Yes, the string ends with \"world!\"" << std::endl;
  } else {
    std::cout << "No, the string does not end with \"world!\"" << std::endl;
  }

  // "world" で終わるか確認
  if (str.ends_with("world")) {
    std::cout << "Yes, the string ends with \"world\"" << std::endl;
  } else {
    std::cout << "No, the string does not end with \"world\"" << std::endl;
  }

  return 0;
}

出力

Yes, the string ends with "world!"
No, the string does not end with "world"

補足

  • ends_with 関数は C++20 で導入されました。
  • C++17 以前では、std::string::compare 関数などを用いて同様の処理を実装できます。

応用例

  • ファイル名の拡張子を判別する
  • 文字列の末尾に特定の文字列が付いているかどうかを確認する
  • 入力された文字列が有効な値かどうかを検証する


C++ std::basic_string::ends_with 関数のサンプルコード

#include <iostream>
#include <string>

bool is_png_file(const std::string& filename) {
  return filename.ends_with(".png");
}

int main() {
  std::string filename = "image.png";

  if (is_png_file(filename)) {
    std::cout << "The file is a PNG file." << std::endl;
  } else {
    std::cout << "The file is not a PNG file." << std::endl;
  }

  return 0;
}

出力

The file is a PNG file.

文字列の末尾に特定の文字列が付いているかどうかを確認する

#include <iostream>
#include <string>

bool ends_with_exclamation_mark(const std::string& str) {
  return str.ends_with("!");
}

int main() {
  std::string str = "Hello, world!";

  if (ends_with_exclamation_mark(str)) {
    std::cout << "The string ends with an exclamation mark." << std::endl;
  } else {
    std::cout << "The string does not end with an exclamation mark." << std::endl;
  }

  return 0;
}

出力

The string ends with an exclamation mark.

入力された文字列が有効な値かどうかを検証する

#include <iostream>
#include <string>

bool is_valid_email_address(const std::string& email) {
  return email.ends_with("@example.com");
}

int main() {
  std::string email;

  std::cout << "メールアドレスを入力してください: ";
  std::cin >> email;

  if (is_valid_email_address(email)) {
    std::cout << "有効なメールアドレスです。" << std::endl;
  } else {
    std::cout << "無効なメールアドレスです。" << std::endl;
  }

  return 0;
}

出力例

メールアドレスを入力してください: [email protected]
有効なメールアドレスです。

部分一致の確認

ends_with 関数は完全一致のみを検出しますが、部分一致を検出したい場合は、以下の方法を用いることができます。

#include <iostream>
#include <string>

bool contains(const std::string& str, const std::string& sub) {
  return str.find(sub) != std::string::npos;
}

int main() {
  std::string str = "Hello, world!";

  if (contains(str, "world")) {
    std::cout << "The string contains \"world\"." << std::endl;
  } else {
    std::cout << "The string does not contain \"world\"." << std::endl;
  }

  return 0;
}

出力

The string contains "world".

大文字と小文字の区別を無視する

ends_with 関数は大文字と小文字を区別しますが、区別を無視したい場合は、以下の方法を用いることができます。

#include <iostream>
#include <string>
#include <algorithm>

bool ends_with_ignore_case(const std::string& str, const std::string& sub) {
  std::string lower_str = str;
  std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);

  std::string lower_sub = sub;
  std::transform(lower_sub.begin(), lower_sub.end(), lower_sub.begin(), ::tolower);

  return lower_str.ends_with(lower_sub);
}

int main() {
  std::string str = "Hello, world!";

  if (ends_with_ignore_case(str, "WORLD")) {
    std::cout << "The string ends with \"WORLD\" (ignoring case)." << std::endl;
  } else {
    std::cout << "The string does not end with \"WORLD\" (ignoring case)." << std::endl;
  


C++ std::basic_string::ends_with 関数の代替方法

std::string::compare 関数

bool ends_with(const std::string& str, const std::string& sub) {
  return str.compare(str.size() - sub.size(), sub.size(), sub) == 0;
}

std::find_end 関数

bool ends_with(const std::string& str, const std::string& sub) {
  return std::find_end(str.begin(), str.end(), sub.begin(), sub.end()) == str.end();
}

自作関数

bool ends_with(const std::string& str, const std::string& sub) {
  for (size_t i = str.size() - sub.size(); i < str.size(); ++i) {
    if (str[i] != sub[i - str.size() + sub.size()]) {
      return false;
    }
  }
  return true;
}

これらの方法は、ends_with 関数よりも冗長になりますが、C++17 以前の環境でも使用できます。

注意事項

  • 上記の方法は、すべて大文字と小文字を区別します。
  • 部分一致を検出したい場合は、std::find 関数などを用いる必要があります。

ends_with 関数は、文字列の末尾が特定の文字列で終わっているかどうかを簡単に検証できる便利な関数です。C++20 以降を使用している場合は、ends_with 関数の使用を検討することをお勧めします。C++17 以前を使用している場合は、上記の方法を参考にしてください。




C++ Stringsにおけるstd::basic_string_view::rfind

概要std::basic_string_view::rfind は、部分文字列と検索を開始する位置を受け取り、部分文字列が最後に出現する位置を返します。部分文字列が見つからない場合は、std::basic_string_view::npos が返されます。



C++ストリングクラスにおけるstd::basic_string::find_first_not_of関数:詳細解説とサンプルコード

std::basic_string::find_first_not_of関数は、指定された文字列または文字範囲内で、最初の除外文字が現れる位置を検索します。除外文字とは、検索対象文字列に含まれていない文字のことです。詳細解説関数宣言引数s: 除外文字列または文字範囲の先頭ポインタ


C++ Strings で std::basic_string::npos を使用したサンプルコード

npos の意味最大値: npos は、size_t 型で表現可能な最大値に設定されています。文字列の終端: find() や find_first_of() などの関数で npos を引数として渡すと、文字列の終端まで検索することを意味します。


C++で文字コード変換をマスターしよう!std::btowcの使い方とサンプルコード

この関数を使うことで、異なるエンコード間で文字列を効率的に変換したり、マルチバイト文字を扱うプログラムを作成することができます。std::btowcは以下の形式で定義されています。c: 変換する単一バイト文字std::wint_t: 変換結果のワイド文字


C++の「std::wcstoimax」でワイド文字列を整数に変換:詳細解説とサンプルコード

概要std::wcstoimax は、C++ の標準ライブラリに含まれる関数で、ワイド文字列 (wstring) を指定した基数に基づいて整数値に変換します。これは、std::stoi() 関数のワイド文字列バージョンと考えることができます。



C++ の文字列操作:std::basic_string の演算子徹底解説

+ 演算子 を使って、2つの文字列を連結することができます。==, !=, <, >, <=, >= 演算子を使って、2つの文字列を比較することができます。比較は、文字列の各文字コードを比較して行われます。+= 演算子 を使って、文字列に文字を追加することができます。


C++ Stringsにおけるstd::basic_string_view::rfind

概要std::basic_string_view::rfind は、部分文字列と検索を開始する位置を受け取り、部分文字列が最後に出現する位置を返します。部分文字列が見つからない場合は、std::basic_string_view::npos が返されます。


C++ストリングクラスにおけるstd::basic_string::find_first_not_of関数:詳細解説とサンプルコード

std::basic_string::find_first_not_of関数は、指定された文字列または文字範囲内で、最初の除外文字が現れる位置を検索します。除外文字とは、検索対象文字列に含まれていない文字のことです。詳細解説関数宣言引数s: 除外文字列または文字範囲の先頭ポインタ


C++ std::atol サンプルコード集: 文字列を数値に変換する様々な方法

std::atol は、cstdlib ヘッダーファイルで定義されている関数です。以下のプロトタイプを持ちます。str: 変換対象となる文字列へのポインタこの関数は、str が指す文字列を解析し、long long int 型の整数に変換して返します。文字列の先頭から、空白文字(isspace で判定される文字)を無視し、最初の非空白文字から解析を開始します。


std::basic_string::crbegin関数とstd::reverse_iteratorの比較

std::basic_string::crbegin は、C++ 標準ライブラリで提供されている std::basic_string クラスのメンバ関数です。この関数は、文字列の逆順を指す 読み取り専用 イテレータを返します。つまり、文字列の最後の文字から最初の文字に向かってイテレートすることができます。