5、计算宇符串长度,通过函数调用的方式实现。程序。c语言
时间: 2024-02-21 18:00:08 浏览: 90
以下是一个计算字符串长度的C语言程序,其中使用了一个函数 `strLength` 来计算字符串长度:
```
#include <stdio.h>
int strLength(char str[]) {
int i = 0;
while (str[i] != '\0') {
i++;
}
return i;
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strLength(str);
printf("字符串长度为:%d\n", len);
return 0;
}
```
在 `strLength` 函数中,我们使用了一个循环来遍历字符串,直到遇到字符串末尾的空字符 `\0` 才停止循环,同时记录循环的次数,即字符串的长度。注意,字符串末尾的空字符也是字符串的一部分,因此长度需要加1。
在主函数中,我们首先定义一个字符数组 `str`,并使用 `scanf` 函数从标准输入中读取一个字符串。然后,我们调用 `strLength` 函数计算字符串长度,并将结果打印输出。
您可以根据需要修改程序,例如可以使用指针来实现字符串长度的计算。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)