C++如何计算字符串长度
时间: 2023-09-26 20:11:09 浏览: 43
在C语言中,计算字符串长度可以使用库函数strlen()。例如:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
printf("The length of the string is: %d\n", len);
return 0;
}
```
输出结果为 "The length of the string is: 13"。
相关问题
c++计算字符串长度
在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后返回。