如何获取std :: string中的字符数? [英] How to get the number of characters in a std::string?

查看:489
本文介绍了如何获取std :: string中的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中获取字符串中的字符数?

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

推荐答案

如果您使用的是 std :: string ,调用 length()

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

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

如果您使用的是c字符串,请调用 strlen()

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

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

或者,如果您碰巧喜欢使用Pascal风格的字符串(或Joel Spolsky的f *****字符串喜欢称呼它们

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"

这篇关于如何获取std :: string中的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆