用C语言实现3.字符串长度。 题目内容: 编写求字符串长度的函数。在main函数中输入字符串,调用函数并输出其长度。 函数原型: int length(char *p) 输出格式: Please input a string: China↙ The length of the string is 5.
时间: 2024-03-03 11:50:30 浏览: 79
好的,这是一个简单的字符串长度计算程序,以下是用C语言实现的代码:
```c
#include <stdio.h>
int length(char *p);
int main() {
char str[100];
printf("Please input a string: ");
scanf("%s", str);
printf("The length of the string is %d.\n", length(str));
return 0;
}
int length(char *p) {
int len = 0;
while (*p != '\0') {
len++;
p++;
}
return len;
}
```
程序中,我们定义了一个名为`length`的函数,它接受一个指向字符数组的指针作为参数,并返回该字符串的长度。在`main`函数中,我们先输入一个字符串,然后调用`length`函数并输出结果。
注意,我们在`length`函数中使用了指针来遍历字符串,直到遇到字符串结束的`\0`字符为止。同时,我们使用了一个计数器`len`来记录字符串的长度。最后,函数返回计数器的值,即为字符串的长度。
希望这个例子能帮助你更好地理解如何使用C语言处理字符串。
相关问题
C语言实现:实现求字符串长度的函数,不得调用C语言提供的求字符串长度的函数
如果不能使用C语言提供的`strlen()`函数,我们可以手动遍历字符串,直到遇到`\0`终止符为止。下面是一个简单的示例:
```c
#include <stdio.h>
// 自定义求字符串长度的函数
int custom_string_length(const char *str) {
int len = 0; // 初始化长度为0
while (*str != '\0') { // 当字符不是结束符时,逐个计数
len++;
str++; // 移动指针到下一个字符
}
return len;
}
int main() {
const char* str1 = "abc";
int length1 = custom_string_length(str1);
printf("Length of '%s': %d\n", str1, length1);
const char* str2 = "abcde";
int length2 = custom_string_length(str2);
printf("Length of '%s': %d\n", str2, length2);
return 0;
}
```
在这个`custom_string_length`函数里,我们通过一个while循环,当遇到字符串结束标志'\0'时停止计数,从而得到字符串的实际长度。
用C语言实现编写求字符串长度的函数。在main函数中输入字符串,调用函数并输出其长度。 函数原型: int length(char *p) 输出格式: Please input a string: China↙ The length of the string is 5.
好的,下面是代码实现:
```c
#include <stdio.h>
int length(char *p);
int main() {
char str[100];
printf("Please input a string: ");
scanf("%s", str);
int len = length(str);
printf("The length of the string is %d.\n", len);
return 0;
}
int length(char *p) {
int len = 0;
while (*p != '\0') {
len++;
p++;
}
return len;
}
```
我们定义了一个 `length` 函数,它接收一个指向字符数组的指针,然后遍历这个数组,每遇到一个非空字符就将计数器加一,直到遍历完成,最后返回计数器的值。在 `main` 函数中,我们先输入一个字符串,然后调用 `length` 函数并输出它的返回值即可。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)