21xrx.com
2025-03-28 15:41:53 Friday
文章检索 我的文章 写文章
C++字符串长度函数的实现
2023-07-07 01:38:11 深夜i     14     0
C++ 字符串 长度函数 实现

C++字符串长度函数(strlen)用于测量一个C-style字符串的长度,即该字符串中包含字符的数量。在C++中,字符串以null('\0')字符结尾。因此,strlen函数在遍历字符串时,会计算到此null字符,而不会将其计入字符串长度。

下面介绍一种实现C++字符串长度函数的方法:

#include <iostream>
using namespace std;
int strlen(const char* str) {
  int len = 0;
  while(*(str+len) != '\0') {
    len++;
  }
  return len;
}
int main() {
  char str[] = "Hello, world!";
  int len = strlen(str);
  cout << "The length of the string is: " << len << endl;
  return 0;
}

在上述代码中,使用了指针来代替数组下标来遍历字符串。其中,str+len表示指向str字符串中第len个字符的指针,使用*取值符号获得该指针指向的字符。

此外,上述代码中的字符串是以数组的形式来声明的,而字符数组在C++中是一种比较基础且常用的数据类型。而C++也提供了一些STL库中的字符串类(如std::string),能够更方便地操作字符串。

总之,C++字符串长度函数是C-style字符串的重要组成部分,通过使用指针进行遍历,可以方便地计算出字符串的长度。

  
  

评论区