在C语言中,我们知道字符串基本上是一个以'\ 0'结尾的字符数组。因此,要对字符串进行操作,我们定义了字符数组。但是在C ++中,标准库为我们提供了将字符串用作基本数据类型(作为整数)的便利。我们可以使用length()函数轻松地找到字符串的长度。
原型:
size_t string.length();
参数:无
返回类型: size_t
示例
Like we define and declare, string s1="Include", s2="Help"; int i=s1.length(); //7--- int j=s2.length(); //4--- After concatenating: string s3=s1+s2; (s3 is "IcludeHelp") int k=s3.length(); //11------ string s4=s2+s1; (s4 is "HelpInclude") int r=s4.length(); //11------
请记住,需要在“”下定义一个字符串变量(文字)。“ a”是字符,而“ a”是字符串。
需要的头文件:
#include <string> Or #include <bits/stdc++.h>
C ++程序演示string::length()函数的示例
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cout<<"enter string\n";
cin>>s;
cout<<"length of the string is: "<<s.length();
return 0;
}输出结果
enter string NHOOO length of the string is: 11