std::basic_string<CharT,Traits,Allocator>::size, std::basic_string<CharT,Traits,Allocator>::length
From cppreference.com
< cpp | string | basic string
| size_type size() const; |
(1) | (C++11 以降 noexcept) (C++20 以降 constexpr) |
| size_type length() const; |
(2) | (C++11 以降 noexcept) (C++20 以降 constexpr) |
文字列内のCharT要素の数を返します。つまり、std::distance(begin(), end())です。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
文字列内のCharT要素の数。
[編集] 計算量
|
未規定 |
(C++11まで) |
|
Constant |
(C++11以降) |
[編集] 注記
std::stringの場合、要素はバイト(char型のオブジェクト)であり、UTF-8のようなマルチバイトエンコーディングが使用されている場合、文字とは異なります。
[編集] 例
このコードを実行
#include <cassert> #include <iterator> #include <string> int main() { std::string s("Exemplar"); assert(8 == s.size()); assert(s.size() == s.length()); assert(s.size() == static_cast<std::string::size_type>( std::distance(s.begin(), s.end()))); std::u32string a(U"ハロー・ワールド"); // 8 code points assert(8 == a.size()); // 8 code units in UTF-32 std::u16string b(u"ハロー・ワールド"); // 8 code points assert(8 == b.size()); // 8 code units in UTF-16 std::string c("ハロー・ワールド"); // 8 code points assert(24 == c.size()); // 24 code units in UTF-8 #if __cpp_lib_char8_t >= 201907L std::u8string d(u8"ハロー・ワールド"); // 8 code points assert(24 == d.size()); // 24 code units in UTF-8 #endif }
[編集] 関連項目
| 文字列が空かどうかをチェックする (public member function) | |
| 最大文字数を返す (public member function) | |
| 文字数を返す (public member function of std::basic_string_view<CharT,Traits>) |