c++计算字符串长度
时间: 2023-08-03 19:25:06 浏览: 113
在C++中,可以使用库函数`strlen`计算字符串长度,该函数定义在头文件`<cstring>`中。示例如下:
```c++
#include <cstring>
#include <iostream>
int main() {
char str[] = "Hello, world!";
int len = std::strlen(str);
std::cout << "The length of the string is " << len << std::endl;
return 0;
}
```
输出结果为:
```
The length of the string is 13
```
相关问题
c++ 计算字符串数组长度
字符串数组长度可以通过使用 sizeof 运算符来计算,例如:
```
char str[] = "Hello, World!";
int length = sizeof(str) / sizeof(str[0]);
```
这里的 sizeof(str) 将返回整个字符串数组所占用的字节数,而 sizeof(str[0]) 将返回一个字符的字节数。通过这两个值的比较,我们可以得出字符串数组中元素的数量,从而计算出字符串数组的长度。
用C++计算字符串的长度
可以使用库函数strlen来计算字符串的长度,具体实现方法如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:\n");
scanf("%s", str);
int len = strlen(str);
printf("该字符串的长度为:%d\n", len);
return 0;
}
```
阅读全文
相关推荐













