不能使用strlen函数
时间: 2023-10-28 08:07:37 浏览: 45
如果不能使用`strlen`函数,那么可以使用循环来计算字符串的长度。可以使用如下代码:
```c
int length = 0;
while (string[length] != '\0') {
length++;
}
```
这段代码会在字符串末尾找到 `'\0'` 字符前一直循环,每次循环 `length` 值加 1,直到找到 `'\0'` 字符为止,此时 `length` 的值就是字符串的长度。
相关问题
使用strlen函数
strlen函数是一个C标准库函数,用于计算字符串的长度。它的参数为一个字符指针,返回值为一个无符号整数,即字符串的长度。使用strlen函数可以方便地计算字符串的长度,而不需要手动遍历字符串。下面是一个使用strlen函数计算字符串长度的示例代码:
```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
```
输入一个字符串,统计该字符串的字符个数。 要求: 使用指针实现统计。 不能使用strlen函数。 字符串中包含空格。
好的,可以使用指针和字符数组来实现。以下是实现代码:
```c
#include <stdio.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN];
printf("请输入一个字符串:\n");
fgets(str, MAX_LEN, stdin);
int count = 0;
char* p = str;
while (*p != '\0') {
if (*p != '\n') { // 排除换行符
count++;
}
p++;
}
printf("该字符串的字符个数为:%d\n", count);
return 0;
}
```
代码中使用了 `fgets()` 函数获取输入的字符串,遍历字符串时使用指针 `p`,判断字符是否为换行符并统计字符个数。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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://csdnimg.cn/download_wenku/file_type_ask_c1.png)