字符序列或字符的线性数组称为字符串。其声明与定义其他数组相同。
数组的长度是字符串中的字符数。有很多内置方法和其他方法来查找字符串的长度。在这里,我们讨论了5种不同的方法来在C ++中查找字符串的长度。
1)使用strlen()C的方法-此函数返回C的整数值。为此,您需要以字符数组的形式传递字符串。
strlen()方法使用的程序#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char charr[] = "I Love Nhooo";
   int length = strlen(charr);
   cout << "the length of the character array is " << length;
   return 0;
}输出结果
the length of the character array is 21
2)使用size()c ++的方法-它包含在C ++的字符串库中。返回字符串中字符数的整数值。
size()方法使用的程序#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love nhooo";
   int length = str.size();
   cout << "the length of the string is " << length;
   return 0;
}输出结果
The length of the string is 21
3)使用for循环-此方法不需要任何功能。它遍历数组并计算其中的元素数。循环运行直到遇到“ / 0”。
#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love nhooo";
   int i;
   for(i=0; str[i]!='\0'; i++){ }
      cout << "the length of the string is " << i;
   return 0;
}输出结果
The length of the string is 21
4)使用length()方法-在C ++中,它们是length()字符串库中的一种方法,该方法返回字符串中的字符数。
length()方法#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love nhooo";
   int length = str.length();
   cout << "the length of the string is " << length;
      return 0;
}输出结果
The length of the string is 21
5)使用while循环查找字符串的长度-您也可以使用while循环计算字符串中的字符数。要计算字符数,必须在while循环中使用一个计数器,并将结束条件指定为字符串的!='\ 0'。
#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love nhooo";
   int length = 0;
   while(str[length] !='\0' ){
      length++;
   }
   cout<<"The length of the string is "<< length;
   return 0;
}输出结果
The length of the string is 21