C++中查找字符串长度的五种不同方法?


一系列字符或字符的线性数组称为字符串。它的声明与定义其他数组相同。

数组的长度是字符串中字符的数量。有很多内置方法和其他方法可以查找字符串的长度。在这里,我们将讨论在 C++ 中查找字符串长度的五种不同方法。

1) 使用 C 的 strlen() 方法 - 此函数返回 C 的整数值。为此,您需要以字符数组的形式传递字符串。

使用 strlen() 方法的示例程序

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char charr[] = "I Love Tutorialspoint";
   int length = strlen(charr);
   cout << "the length of the character array is " << length;
   return 0;
}

输出

the length of the character array is 21

2) 使用 c++ 的 size() 方法 - 它包含在 C++ 的字符串库中。返回字符串中字符数量的整数值。

使用 size() 方法的示例程序

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   int length = str.size();
   cout << "the length of the string is " << length;
   return 0;
}

输出

The length of the string is 21

3) 使用 for 循环 - 此方法不需要任何函数。它遍历数组并计算其中的元素数量。循环运行直到遇到“/0”。

使用 for 循环查找长度的程序

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   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 tutorialspoint";
   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’ 用于字符串。

使用 while 循环查找字符串长度的程序

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "I love tutorialspoint";
   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

更新于:2019年8月8日

2K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.