21xrx.com
2024-09-20 00:47:52 Friday
登录
文章检索 我的文章 写文章
C++如何计算字符数组的长度?
2023-06-26 18:56:51 深夜i     --     --
C++ 计算 字符数组 长度

计算字符数组的长度是C++编程中常见的任务之一。字符数组是一种存储字符序列的数据结构,一般用于存储字符串。在C++中,字符数组的长度可以通过两种方法来计算:使用字符串库函数或手动计算。

使用字符串库函数

C++中的字符串库函数提供了许多用于处理字符串和字符数组的函数,其中最常用的是strlen()函数。这个函数接受一个字符数组作为参数,并返回该数组中的字符数,不包括字符串的结束符。下面是一个使用strlen()函数的示例程序:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str[] = "Hello, world!";

  int len = strlen(str);

  cout << "The length of the string is " << len << endl;

  return 0;

}

运行这个程序,输出为:


The length of the string is 13

手动计算字符数组的长度

除了使用strlen()函数来计算字符数组的长度之外,我们还可以手动计算字符数组的长度。这个方法更为基础,也更为直观。我们只需要遍历字符数组,并计算数组中的字符总数就可以了。

下面是一个手动计算字符数组长度的示例程序:


#include <iostream>

using namespace std;

int main()

{

  char str[] = "Hello, world!";

  int len = 0;

  while (str[len] != '\0') // '\0'为字符串的结束符

  {

    len++;

  }

  cout << "The length of the string is " << len << endl;

  return 0;

}

运行这个程序,输出为:


The length of the string is 13

综合来说,计算字符数组长度是C++编程中的一个基础任务。无论是使用strlen()函数还是手动计算,都能够很容易地得到字符数组的长度。在实际开发中,我们可以根据不同的需求来选择合适的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复