How to get the number of characters in a std::stri

2019-01-05 00:27发布

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

11条回答
手持菜刀,她持情操
2楼-- · 2019-01-05 00:40

If you're using old, C-style string instead of the newer, STL-style strings, there's the strlen function in the C run time library:

const char* p = "Hello";
size_t n = strlen(p);
查看更多
Deceive 欺骗
3楼-- · 2019-01-05 00:41
string foo;
... foo.length() ...

.length and .size are synonymous, I just think that "length" is a slightly clearer word.

查看更多
放我归山
4楼-- · 2019-01-05 00:48

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"
查看更多
SAY GOODBYE
5楼-- · 2019-01-05 00:49

for an actual string object:

yourstring.length();

or

yourstring.size();
查看更多
三岁会撩人
6楼-- · 2019-01-05 00:51

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 <iostream>
#include <string.h>

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
查看更多
The star\"
7楼-- · 2019-01-05 00:52
std::string str("a string");
std::cout << str.size() << std::endl;
查看更多
登录 后发表回答