C语言求字符串的长度详解

2022-06-25 08:45:23

C语言中的字符串是通过字符数组的形式来模拟的,字符数组本质上就是一个普通的数组,只不过每个元素的数据类型是char,C风格字符会在数组的最后一个元素中填充成\0作为字符串结束的标记,虽然C语言的字符串是字符数组,但也是可以用一个char*指向字符数组的第一个元素,然后用这个指针来表示字符串

(1)创建临时变量的方式求字符串的长度

#include <stdio.h>
#include <stdlib.h>
int Strlen(char* str){
	int count = 0;   //创建了临时变量
	while (*str != '\0'){
		++count;
		++str;
	}
	return count;
}
int main(){
	printf("%d\n", Strlen("hello world"));
	system("pause");
	return 0;
}

运行结果为在这里插入图片描述

(2)不创建临时变量的方式求字符串的长度(递归方式)

#include <stdio.h>
#include <stdlib.h>
int Strlen(char* str){
	if (*str == '\0'){       //str指向的是一个空字符串
		return 0;
	}
	return 1 + Strlen(str + 1);  //str指向的是当前字符串中的一个元素
}                                              //比如:hello 如果指向的是h  那就是1+"ello"字符串
int main(){                              //的长度
	printf("%d\n", Strlen("hello world"));
	system("pause");
	return 0;
}

运行结果为在这里插入图片描述

  • 作者:#define微光
  • 原文链接:https://blog.csdn.net/weixin_43224539/article/details/83108635
    更新时间:2022-06-25 08:45:23