21xrx.com
2024-06-03 06:07:20 Monday
登录
文章检索 我的文章 写文章
C++中如何获取字符串的长度
2023-07-08 09:52:43 深夜i     --     --
C++ 字符串 长度 获取

在C++中,获取字符串的长度可以使用两种方式:使用strlen函数和直接使用字符串的length方法。以下是两种方法的详细介绍:

1.使用strlen函数

strlen是一个C语言库函数,声明在 头文件中。该函数的作用是返回一个字符串的长度,也就是字符数的个数。具体用法如下:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

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

  int len = strlen(str);

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

  return 0;

}

输出结果为:


The length of the string "Hello, world!" is: 13

需要注意的是,使用strlen函数时必须确保字符串以null字符(\0)结尾。否则,该函数将无法正确计算字符串长度并可能导致程序错误。

2.使用字符串的length方法

C++中的标准库string类提供了一个名为length的成员方法,可以用于获取一个字符串的长度,其用法如下:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "Hello, world!";

  int len = str.length();

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

  return 0;

}

输出结果为:


The length of the string "Hello, world!" is: 13

需要注意的是,使用string类获取字符串长度时不需要担心null字符的问题,因为string类自动将字符串以null字符结尾并在内部处理。

总结

无论是使用C库函数strlen还是标准库string类的length方法,都可以轻松获取一个字符串的长度。在选择方法时,可以根据实际情况和个人喜好进行选择。如果字符串是以字符数组的形式存在,那么使用strlen函数将更为方便。如果字符串以string对象的形式存在,那么使用string类的length方法将更容易阅读和理解。

  
  

评论区

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