定义函数str_length,函数原型是int str_length(char *p), 函数功能是,统计指针p指向的字符串中字符的个数(碰见'\0'结束统计)。main函数内容如下
时间: 2024-02-27 12:52:54 浏览: 19
好的,下面是函数str_length的实现代码:
```c
#include <stdio.h>
int str_length(char *p);
int main() {
char str[] = "Hello, world!";
int len = str_length(str);
printf("The length of the string is: %d\n", len);
return 0;
}
int str_length(char *p) {
int len = 0;
while (*p != '\0') {
len++;
p++;
}
return len;
}
```
在这个代码中,我们定义了一个字符串数组`str`并初始化为`"Hello, world!"`,然后调用`str_length`函数统计字符串的长度。`str_length`函数使用了一个指针`p`遍历字符串,统计字符的个数,并返回长度。在`main`函数中,我们将`str_length`函数的返回值打印出来,就得到了字符串的长度。
相关问题
编写一个函数int strlength(char *str)求字符串str的长度
好的,这是一个简单的求字符串长度的函数实现:
```c
int strlength(char *str) {
int len = 0;
while (*str) {
len++;
str++;
}
return len;
}
```
这个函数的原理很简单,就是利用指针遍历字符串,计算字符的个数,直到遇到字符串的结尾符`\0`。
写一函数,求一个字符串的长度。在main函数中输入字 符串,并输出其长度。函数定义如下: int length(char *p)
以下是实现函数的代码:
```c
#include <stdio.h>
int length(char *p) {
int len = 0;
while (*p != '\0') {
len++;
p++;
}
return len;
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = length(str);
printf("该字符串的长度为:%d\n", len);
return 0;
}
```
函数 `length` 接收一个字符指针 `p`,使用一个循环遍历指针所指向的字符串,每遇到一个非空字符就将长度加 1。最后返回字符串的长度。
在 `main` 函数中,首先定义一个字符数组 `str`,然后使用 `scanf` 函数从标准输入读入一个字符串。然后调用 `length` 函数获取字符串长度并打印输出。
相关推荐
![](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)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)