c++ の compare 関数の使い方は?

C++では、compare 関数は2つの文字列を比較するために使用されるメソッドの1つです。通常、文字列の大小関係を比較して、比較結果を表す整数を返します。compare 関数の構文は次のとおりです。

int compare(const string& str) const;
int compare(size_t pos, size_t len, const string& str) const;
int compare(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
int compare(const char* s) const;
int compare(size_t pos, size_t len, const char* s) const;
int compare(size_t pos, size_t len, const char* s, size_t n) const;

str は、現在の文字列と比較すべきもう一つの文字列、pos は、現在の文字列内で比較を開始する開始位置、len は、現在の文字列で比較すべき文字数、subpos と sublen は、str 内のサブ文字列と比較すべき開始位置と文字数、s は、空文字で終了する C スタイル文字列、n は、比較すべき文字数です。

compare関数の戻り値は次のいずれかです。

  1. 現在の文字列が str より小さい場合は、負の整数を返します。
  2. 現在の文字列がstrと等しければ、0を返す。
  3. 現文字列がstrより大きければ正の数値を返す

compare関数は大文字と小文字を区別するため、文字のASCIIコード値で比較を行います。大文字と小文字を区別しない比較を行う場合は、strcasecmp関数またはstricmp関数を使用することができます。

bannerAds