21xrx.com
2024-06-03 03:45:29 Monday
登录
文章检索 我的文章 写文章
C++代码:如何求字符串长度
2023-07-08 13:55:03 深夜i     --     --
C++ 字符串 长度

在C++中,字符串操作是编程中最常见的操作之一。其中求字符串长度也是十分常见的操作。在本文中,我们将通过C++代码介绍如何计算字符串长度。

在C++中,字符串是由字符数组实现的,因此我们可以使用数组的长度来计算字符串长度。例如下面的代码:


#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str[] = "Hello World!";

  int len = strlen(str);

  cout << "Length of the string is: " << len << endl;

  return 0;

}

在上面的代码中,我们首先定义了一个字符数组,存储了一个字符串“Hello World!”。然后,我们使用 `strlen()` 函数来计算字符串的长度。该函数位于 ` ` 头文件中。最后,我们使用 `cout` 输出字符串的长度。

除了使用 `strlen()` 函数外,我们也可以手动计算字符串长度。例如下面的代码:


#include <iostream>

using namespace std;

int main()

{

  char str[] = "Hello World!";

  int len = 0;

  for (int i = 0; str[i] != '\0'; i++)

  {

    len++;

  }

  cout << "Length of the string is: " << len << endl;

  return 0;

}

在上面的代码中,我们定义了一个计数器 `len`,用于计算字符串长度。然后,我们使用 `for` 循环遍历字符串,直到遇到字符串的结束标志 `'\0'`。每遍历到一个字符,计数器 `len` 就加1。最后,我们同样使用 `cout` 输出字符串的长度。

总结来说,求字符串长度是一项非常基本的任务,我们可以使用现成的 `strlen()` 函数或手动计算字符串长度,来完成这个任务。对于刚刚接触C++的初学者来说,这是一个十分基础且必要的操作。

  
  

评论区

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