字符串库函数 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;
}