21xrx.com
2025-06-18 10:52:04 Wednesday
文章检索 我的文章 写文章
C++中字符串数组长度的获取
2023-07-06 18:11:38 深夜i     27     0
C++ 字符串数组 长度 获取

C++是一种广泛使用的编程语言,支持字符串数组类型,但是在使用字符串数组时有时需要确定数组的长度。这里介绍几种获取C++字符串数组长度的方法。

方法一:使用strlen函数

strlen是C++中的一个标准库函数,用于计算字符串的长度。可以通过调用strlen函数获取字符串数组长度。

例如,下面的代码演示了如何使用strlen函数获取一个字符串数组的长度:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  char str[] = "Hello World!";
  int len = strlen(str);
  cout << "String length is " << len << endl;
  return 0;
}

输出:

String length is 12

方法二:使用sizeof运算符

在C++中,sizeof运算符用于计算类型或变量的大小。可以通过将字符串数组的大小除以单个字符的大小(即1)来计算字符串数组的长度。

例如,下面的代码演示了如何使用sizeof运算符获取一个字符串数组的长度:

#include <iostream>
using namespace std;
int main()
{
  char str[] = "Hello World!";
  int len = sizeof(str) / sizeof(char) - 1;
  cout << "String length is " << len << endl;
  return 0;
}

输出:

String length is 12

方法三:手动计算

可以手动计算字符串数组的长度,即循环遍历数组并计数,直到遇到字符串的结尾符'\0'为止。

例如,下面的代码演示了如何手动计算一个字符串数组的长度:

#include <iostream>
using namespace std;
int main()
{
  char str[] = "Hello World!";
  int len = 0;
  while (str[len] != '\0')
    len++;
  cout << "String length is " << len << endl;
  return 0;
}

输出:

String length is 12

以上是三种获取C++字符串数组长度的方法,可以根据自己的需求选择使用。

  
  

评论区