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

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

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

12条回答
  •  猫巷女王i
    2020-11-28 04:47

    If you're using a std::string, call length():

    std::string str = "hello";
    std::cout << str << ":" << str.length();
    // Outputs "hello:5"
    

    If you're using a c-string, call strlen().

    const char *str = "hello";
    std::cout << str << ":" << strlen(str);
    // Outputs "hello:5"
    

    Or, if you happen to like using Pascal-style strings (or f***** strings as Joel Spolsky likes to call them when they have a trailing NULL), just dereference the first character.

    const char *str = "\005hello";
    std::cout << str + 1 << ":" << *str;
    // Outputs "hello:5"
    

提交回复
热议问题