编写一个函数,使用指针计算出一个字符串的长度。
时间: 2024-06-18 07:05:28 浏览: 17
编写一个函数,使用指针计算出一个字符串的长度,可以按照以下方式实现:
```c++
#include <iostream>
using namespace std;
int strLength(char* str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
int main() {
char str[] = "Hello, world!";
int length = strLength(str);
cout << "The length of the string is " << length << endl;
return 0;
}
```
在这个示例中,函数 `strLength()` 接受一个指向字符数组的指针作为参数,然后使用指针遍历字符串并计算出其长度,最后返回长度值。在主函数中,我们定义了一个字符数组并将其作为参数传递给 `strLength()` 函数,以计算出字符串的长度。
相关问题
编写一个函数计算一个字符串的长度,并在主函数输出长度,用指针完成
下面是使用指针完成计算字符串长度的代码示例:
```c
#include <stdio.h>
int str_len(char *str)
{
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
int main()
{
char str[] = "hello world";
int len = str_len(str);
printf("The length of \"%s\" is %d\n", str, len);
return 0;
}
```
在上面的代码中,`str_len` 函数接受一个指向字符串的指针作为参数,并使用指针遍历字符串中的每个字符,直到遇到字符串结束符 `\0`。在遍历过程中,每次遇到一个非结束符的字符,就将长度加 1。最后返回计算得到的字符串长度。
在主函数中,我们定义了一个字符串 `str`,并使用 `str_len` 函数计算其长度,并将结果输出。
用指针1.编写一个程序计算一个字符串的长度。
可以通过遍历字符串中的每个字符并计数的方式来计算字符串的长度。以下是使用指针的实现方法:
```c
#include <stdio.h>
int main() {
char str[100];
char *p;
int len = 0;
printf("输入一个字符串:");
fgets(str, 100, stdin);
p = str; // 将指针指向字符串的首地址
while (*p != '\0') { // 遍历字符串中的每个字符
len++;
p++;
}
printf("字符串长度为:%d\n", len);
return 0;
}
```
首先,我们定义了一个字符数组 `str` 和一个指向字符类型的指针 `p`。然后,使用 `fgets()` 函数从标准输入中获取字符串并将其存储在 `str` 数组中。
接着,将 `p` 指针指向字符串 `str` 的首地址。通过 `while` 循环遍历整个字符串,每遍历一个字符就将长度 `len` 加 1。最后输出字符串长度即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)