21xrx.com
2025-07-10 08:50:45 Thursday
文章检索 我的文章 写文章
C++中如何获取字符串长度
2023-07-02 10:45:19 深夜i     13     0
字符串长度 C++ 获取 strlen函数 string类

在C++语言中,字符串是一组由字符组成的数组,以'\0'结尾。在这种情况下,需要确定字符串的长度,才能进行操作。在本文中,我们将介绍如何获取一个C++字符串的长度。

一、使用strlen()函数

C++中有一个内置函数,称为strlen()函数。它用于计算字符串的长度,不包括'\0'结束符。以下是一个字符串长度计算的示例代码:

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

二、使用while循环

我们可以使用while循环来计算字符串长度。该循环将在字符串的每个字符上迭代,直到遇到'\0'为止。

以下是使用while循环计算字符串长度的示例代码:

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

三、使用for循环

使用for循环也可以计算字符串长度。以下是使用for循环计算字符串长度的示例代码:

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

总结

以上是在C++中获取字符串长度的三种方法。如果您需要计算C++字符串的长度,请使用上述任一方法即可。在需要使用C++字符串长度的任何情况下,都应使用可靠的方法来获取其长度。

  
  

评论区