您的位置:首页 > 编程语言 > C语言/C++

c语言中strlen的几种写法

2014-08-22 14:56 253 查看
一.指针
1(指针的减法运算)2个指针的相减得到字符串的长度
#include <stdio.h>
#include <stdlib.h>
int strlen(char *s);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
return 0;
}
int strlen(char *s){
char *p=s;
while(*p!='\0'){
p++;
}
return p-s;
}
2 1个指针和1个参数 通过参数的累加得到字符串的长度<pre name="code" class="objc">#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int strlen(char *s);
int main(int argc, char *argv[]) {
return 0;
}
int strlen(char *s){
int n;
for(n=0;*s!='\0';s++){
n++;
}
return n;
}


二.数组和一个参数

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int strlen(char s[]);
int main(int argc, char *argv[]) {
return 0;
}
int strlen(char s[]){
int i;
i=0;
while(s[i]!='\0'){
i++;
}
return i;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: