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

server side programmingprogrammingc++

这里我们将看到五种不同的方法来获取 C++ 中的字符串长度。在 C++ 中,我们可以使用传统的字符数组字符串,C++ 也有 String 类。在不同领域,有不同的方法来计算字符串长度。

C++ String 类有 length() 和 size() 函数。这些可用于获取字符串类型对象的长度。要获取传统 C 类字符串的长度,我们可以使用 strlen() 函数。它位于 cstring 头文件下。另外两种方法很简单。一种是使用 while 循环,另一种是使用 for 循环。

让我们看例子来了解一下。

示例

#include<iostream>
#include<cstring>
using namespace std;
main() {
   string myStr = "这是一个示例字符串";
   char myStrChar[] = "这是一个示例字符串";
   cout << "使用 string::length() 函数确定字符串长度:" << myStr.length() <<endl;
   cout << "使用 string::size() 函数确定字符串长度:" << myStr.size() <<endl;
   cout << "使用 strlen() 函数确定字符串长度(适用于 c like string):" << strlen(myStrChar) <<endl;
   cout << "使用while循环计算字符串长度:";
   char *ch = myStrChar;
   int count = 0;
   while(*ch != '\0'){
      count++;
      ch++;
   }
   cout << count << endl;
   cout << "使用for循环计算字符串长度:";
   count = 0;
   for(int i = 0; myStrChar[i] != '\0'; i++){
      count++;
   }
   cout << count;
}

输出

使用 string::length() 函数计算字符串长度:23
使用 string::size() 函数计算字符串长度:23
使用 strlen() 函数计算字符串长度(用于 c like string):23
使用 while 循环计算字符串长度:23
使用 for 循环计算字符串长度:23

相关文章