c/c++ 中 糟糕的strlen用法----- 知道必不犯

字符串库函数 strlen 大家很熟悉 就是获取字符串的长度。
我们常常会用来作为遍历字符串的界限值
下面有一种写法,是新手最容易忽略的,strlen写法。
请看代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main() {
	char a[] = "hello";

	for (int i = 0; i < strlen(a); i++) {
		//做些事情
	}
	return 0;
}

这种写法 看似简洁,殊不知,每次循环都是要去去执行strlen,strlen是需要计算时间的,所以效率上会有浪费。
所以,我们要优化代码,避免糟糕的代码。
下面给出两种写法:

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main() {
	char a[] = "hello";
	int l = strlen(a);
	for (int i = 0; i < l; i++) {
		//做些事情
	}
	return 0;
}
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int main() {
	char a[] = "hello";
	for (int i = 0; i < a[i]; i++) {
		//做些事情
	}
	return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值