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

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

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

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:40

    When dealing with C++ strings (std::string), you're looking for length() or size(). Both should provide you with the same value. However when dealing with C-Style strings, you would use strlen().

    #include 
    #include 
    
    int main(int argc, char **argv)
    {
       std::string str = "Hello!";
       const char *otherstr = "Hello!"; // C-Style string
       std::cout << str.size() << std::endl;
       std::cout << str.length() << std::endl;
       std::cout << strlen(otherstr) << std::endl; // C way for string length
       std::cout << strlen(str.c_str()) << std::endl; // convert C++ string to C-string then call strlen
       return 0;
    }
    

    Output:

    6
    6
    6
    6
    

提交回复
热议问题