使用递归和非递归实现StrLen()和strLen(),来计算字符串长度.
编程思路:调用函数strLen()
1、键入要计算的字符串;
2、调用函数strLen()判断字符串是否为空,为空返回0,否则返回strLen(a + 1) + 1,表示字符串向后移一位,然后字符串长度加1;
3、打印结果。
编程思路:调用函数StrLen()
1、键入要计算的字符串;
2、调用函数StrLen()判断字符串是否为空,若为空返回count=0,否则继续循环,count自增;
3、打印结果。
具体代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SIZE 100
#if 1
int strLen(char a[]) {
if (a[0] == 0) {
return 0;
}
return strLen(a + 1) + 1;
}
#else
int StrLen(char a[]) {
int count = 0;
while (a[count] != '\0') {
count++;
}
return count;
}
#endif
int main() {
char a[SIZE];
gets(a);
strLen(a);
int count = strLen(a);
//int count = StrLen(a);
printf("%d", count);
system("pause");
return 0;
}
本文介绍使用递归和非递归两种方法实现字符串长度计算的函数。递归方法通过不断递减字符串长度并累加来获得结果;非递归方法则利用循环逐字符计数直至遇到结束符。
1839





