求字符串的长度(不能使用库函数)
时间: 2024-01-14 17:02:43 浏览: 31
可以使用循环遍历字符串的方式来求字符串的长度,具体实现如下:
```python
def strlen(s):
length = 0
for i in s:
length += 1
return length
```
其中,`s` 表示要计算长度的字符串,`length` 表示已经计算的字符个数,循环遍历字符串 `s` 中的每个字符,每遍历一个字符,就将 `length` 的值加 1,最后返回 `length` 的值即可。
相关问题
求字符串长度的库函数c语言
C语言中求字符串长度的库函数是 `strlen()`。
它的函数原型为:
```c
size_t strlen(const char *str);
```
其中,`str` 是指向要求长度的字符串的指针,函数返回值是字符串的长度,类型为 `size_t`。
例如,下面的代码可以计算字符串 `str` 的长度并将其打印出来:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
size_t len = strlen(str);
printf("The length of the string is: %zu\n", len);
return 0;
}
```
输出结果为:
```
The length of the string is: 11
```
c++获取字符串长度库函数
c++获取字符串长度的库函数是strlen(),需要在程序中声明cstring头文件,函数原型为size_t strlen(const char *str)。其中str是指向要检验的空终止字节字符串的指针。除此之外,还可以使用sizeof()运算符来获取字符串长度,但是需要注意的是,sizeof()运算符返回的是字符串占用的字节数,而不是字符串的实际长度。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)