c++计算字符串长度
时间: 2023-08-03 10:25:06 浏览: 60
在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++递归计算字符串长度
c 递归计算字符串长度的代码是:
```
int Length(char* str) {
char* t = str;
if (*t == '\0')
return 0;
else {
t = t + 1;
return (Length(t) + 1);
}
}
```
这段代码通过递归的方式计算字符串的长度。首先将字符串指针赋值给临时指针变量t,如果t指向的字符为空字符('\0'),则返回0,否则将t向后移动一位,然后递归调用Length函数,并将结果加1后返回。
c++ 计算字符串数组长度
字符串数组长度可以通过使用 sizeof 运算符来计算,例如:
```
char str[] = "Hello, World!";
int length = sizeof(str) / sizeof(str[0]);
```
这里的 sizeof(str) 将返回整个字符串数组所占用的字节数,而 sizeof(str[0]) 将返回一个字符的字节数。通过这两个值的比较,我们可以得出字符串数组中元素的数量,从而计算出字符串数组的长度。