C++ 如何使用strlen函数获取字符串的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20180874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:57:29  来源:igfitidea点击:

How to get length of a string using strlen function

c++string

提问by Akash Sharma

I have following code that gets and prints a string.

我有以下获取和打印字符串的代码。

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

int main()
{
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    cout << str;
    getch();
    return 0;
}

But how to count the number of characters in this string using strlen()function?

但是如何使用strlen()函数计算这个字符串中的字符数?

回答by templatetypedef

For C++ strings, there's no reason to use strlen. Just use string::length:

对于 C++ 字符串,没有理由使用strlen. 只需使用string::length

std::cout << str.length() << std::endl;

You should stronglyprefer this to strlen(str.c_str())for the following reasons:

由于以下原因,您应该强烈倾向于这样做strlen(str.c_str())

  1. Clarity: The length()(or size()) member functions unambiguously give back the length of the string. While it's possible to figure out what strlen(str.c_str())does, it forces the reader to pause for a bit.

  2. Efficiency: length()and size()run in time O(1), while strlen(str.c_str())will take Θ(n) time to find the end of the string.

  3. Style: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use std::sortover qsortor std::lower_boundover bsearch, unless some other factors come into play that would affect performance.

  1. 清晰:(length()size())成员函数明确地返回字符串的长度。虽然有可能弄清楚是什么strlen(str.c_str()),但它迫使读者暂停一下。

  2. 效率length()size()在 O(1) 时间内运行,而strlen(str.c_str())将花费 Θ(n) 时间来找到字符串的结尾。

  3. 风格:除非有特殊原因,否则最好选择 C++ 版本的函数而不是 C 版本。这就是为什么,例如,通常认为使用std::sortoverqsortstd::lower_boundover更好bsearch,除非一些其他因素会影响性能。

The only reason I could think of where strlenwould be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which strlendiffers from string::length; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use string::find:

我能想到哪里strlen有用的唯一原因是,如果您有一个嵌入空字符的 C++ 样式字符串,并且您想确定在第一个字符之前出现了多少个字符。(这是strlen与 不同的一种方式string::length;前者在空终止符处停止,后者计算字符串中的所有字符)。但如果是这种情况,只需使用string::find

size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;

Hope this helps!

希望这可以帮助!

回答by masoud

Function strlenshows the number of character before \0and using it for std::stringmay report wrong length.

函数strlen显示之前的字符数,\0使用它std::string可能会报告错误的长度。

strlen(str.c_str()); // It may return wrong length.

In C++, a string can contain \0within the characters but C-style-zero-terminated strings can not but at the end. If the std::stringhas a \0before the last character then strlenreports a length less than the actual length.

在 C++ 中,字符串可以包含\0在字符内,但 C 风格的零终止字符串不能只包含在末尾。如果在最后一个字符之前std::string有一个\0,则strlen报告长度小于实际长度。

Try to use .length()or .size(), I prefer second one since another standard containers have it.

尝试使用.length()or .size(),我更喜欢第二个,因为另一个标准容器有它。

str.size()

回答by Kiril Kirov

Use std::string::sizeor std::string::length(both are the same).

使用std::string::sizestd::string::length(两者相同)。

As you insist to use strlen, you can:

当您坚持使用 时strlen,您可以:

int size = strlen( str.c_str() );

note the usage of std::string::c_str, which returns const char*.

注意 的用法std::string::c_str,它返回const char*

BUTstrlencounts untill it hit \0char and std::stringcan store such chars. In other words, strlencould sometimes lie for the size.

但是strlen计数直到它击中\0字符并且std::string可以存储这样的字符。换句话说,strlen有时可能会因为大小而撒谎。

回答by KeithSmith

If you really, really want to use strlen(), then

如果你真的,真的想使用 strlen(),那么

cout << strlen(str.c_str()) << endl;

else the use of .length() is more in keeping with C++.

否则 .length() 的使用更符合 C++。

回答by user2972135

Manually:

手动:

int strlen(string s)
{
    int len = 0;

    while (s[len])
        len++;

    return len;
}

回答by Orange Blossom

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()

{
    char str[80];

    int i;

    cout<<"\n enter string:";

    cin.getline(str,80);

    int n=strlen(str);

    cout<<"\n lenght is:"<<n;

    getch();

    return 0;

}

This is the program if you want to use strlen . Hope this helps!

如果您想使用 strlen ,这就是程序。希望这可以帮助!

回答by Jakarea Parvez

Simply use

只需使用

int len=str.length();

int len=str.length();