21xrx.com
2024-09-19 09:32:11 Thursday
登录
文章检索 我的文章 写文章
C++如何获取字符串长度?
2023-07-05 05:44:27 深夜i     --     --
C++ 字符串 长度 获取

在C++中,获取字符串的长度是一项非常常见的任务。字符串长度指的是该字符串中的字符数,而不是字符串的字节数。

在C++中,可以使用两种方法来获取字符串的长度。第一种方法是使用C++标准库中的`strlen()`函数。这个函数的作用是计算一个以null结尾的字符串中的字符数。下面是一个使用`strlen()`函数获取字符串长度的示例代码:


#include <iostream>

#include <cstring>

int main()

{

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

  int len = strlen(str);

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

  return 0;

}

输出结果为:


The length of the string is: 13

第二种方法是使用C++标准库中的`string`类。这个类提供了一个名为`size()`的成员函数,它可以返回`string`对象中的字符数。下面是一个使用`string`类获取字符串长度的示例代码:


#include <iostream>

#include <string>

int main()

{

  std::string str = "Hello, World!";

  int len = str.size();

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

  return 0;

}

输出结果与第一个示例代码相同。

无论使用哪种方法,获取字符串的长度都是一个简单的任务。在实际编程中,获取字符串长度是非常重要的一项任务,因为它可以帮助程序员正确地处理字符串,防止越界访问和其他错误。

  
  

评论区

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