How to get the number of characters in a std::string?

前端 未结 12 1002
既然无缘
既然无缘 2020-11-28 03:52

How should I get the number of characters in a string in C++?

12条回答
  •  野性不改
    2020-11-28 04:44

    It depends on what string type you're talking about. There are many types of strings:

    1. const char* - a C-style multibyte string
    2. const wchar_t* - a C-style wide string
    3. std::string - a "standard" multibyte string
    4. std::wstring - a "standard" wide string

    For 3 and 4, you can use .size() or .length() methods.

    For 1, you can use strlen(), but you must ensure that the string variable is not NULL (=== 0)

    For 2, you can use wcslen(), but you must ensure that the string variable is not NULL (=== 0)

    There are other string types in non-standard C++ libraries, such as MFC's CString, ATL's CComBSTR, ACE's ACE_CString, and so on, with methods such as .GetLength(), and so on. I can't remember the specifics of them all right off the top of my head.

    The STLSoft libraries have abstracted this all out with what they call string access shims, which can be used to get the string length (and other aspects) from any type. So for all of the above (including the non-standard library ones) using the same function stlsoft::c_str_len(). This article describes how it all works, as it's not all entirely obvious or easy.

提交回复
热议问题