编写函数 返回值为字符数组长度
时间: 2024-05-06 11:15:34 浏览: 11
以下是一个返回字符数组长度的函数示例:
```c++
int getLength(char arr[]) {
int length = 0;
while (arr[length] != '\0') {
length++;
}
return length;
}
```
该函数接收一个字符数组作为参数,然后使用一个循环遍历数组中的元素,直到遇到字符串的末尾字符'\0'为止。在循环结束时,函数返回字符串的长度。
相关问题
用c语言编写函数int len(char a[100]),返回值为字符数组长度。在main函数中输入字符串,调用该函数。
以下是用 C 语言编写的求字符串长度的函数 `len`:
```c
#include <stdio.h>
#include <string.h>
int len(char a[100]) {
return strlen(a);
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
printf("字符串的长度为:%d\n", len(str));
return 0;
}
```
首先在头文件中引入 `stdio.h` 和 `string.h`,然后定义函数 `len`。该函数接收一个长度为 100 的字符数组 `a`,使用 `strlen` 函数求出该字符串的长度,并将其返回。
在 `main` 函数中,定义一个长度为 100 的字符数组 `str`,使用 `scanf` 函数读入字符串,然后调用 `len` 函数求出字符串长度,并输出结果。
3.编写函数 int len(char a[100]),返回值为字符数组长度。在 main 函数 中输入字符串,调用该函数。
下面是实现该函数的代码:
```c++
#include <iostream>
using namespace std;
int len(char a[100]) {
int count = 0;
while (a[count] != '\0') {
count++;
}
return count;
}
int main() {
char str[100];
cout << "请输入一个字符串:" << endl;
cin >> str;
int length = len(str);
cout << "该字符串长度为:" << length << endl;
return 0;
}
```
该函数通过遍历字符数组,计算除了最后一个结束符'\0'以外的字符个数,从而得到字符数组长度。在 main 函数中,用户输入一个字符串,然后调用该函数计算其长度并输出。