strlen()
、length()
和size()
是用于获取字符串或容器长度的函数。
-
strlen()
是C语言标准库中的函数,用于获取C风格字符串(以null结尾的字符数组)的长度。它的用法是:size_t strlen(const char* str)
。返回的是字符串中字符的个数,不包括null终止符。 -
length()
是C++标准库中字符串类(例如std::string)的成员函数,用于获取字符串的长度。它的用法是:size_t length() const
。返回的是字符串中字符的个数,不包括null终止符。这个函数主要用于字符串类的操作。 -
size()
是C++标准库中容器(例如std::vector、std::list、std::set等)的成员函数,用于获取容器中元素的个数。它的用法是:size_t size() const
。返回的是容器中元素的个数。这个函数适用于任何容器类型。
需要注意的是,strlen()
只适用于C风格字符串,不能用于C++的字符串类(std::string)和其他容器类型。而length()
和size()
适用于C++字符串类和容器,但不能直接用于C风格字符串。
总结:
strlen()
适用于C风格字符串,用于获取字符串长度。示例代码:-
#include<iostream> #include<cstring> using namespace std; int main(){ char a[101],b[101]; cin.get(a,101); int l; l=strlen(a); cout<<l; return 0; }
length()
适用于C++字符串类,用于获取字符串长度。示例代码:-
#include<iostream> using namespace std; int main(){ //char a[101],b[101]; string a; cin>>a; int l; l=a.length(); cout<<l; return 0; }
size()
适用于C++容器,用于获取容器中元素的个数。示例代码:-
#include<iostream> using namespace std; int main(){ //char a[101],b[101]; string a; cin>>a; int l; l=a.size(); cout<<l; return 0; }