1. 程式人生 > >strlen函數實現

strlen函數實現

char [] 長度 while strlen 作用 return null 字符串

原型: int strlen(const char *s);

作用:返回字符串的長度。

方法1:利用中間變量

int strlen(const char *s){
    int i=0;
    while(s[i] != \0){
        i++;
    }
    return i;
}

方法2:利用指針

int strlen(const char *s){
    char *t=s;while(*s){
    s++;
  }
  return s-t; }

方法3:利用遞歸

int strlen(const char *s){
    if(s==NULL) return
-1; if(*s==\0) return 0; return (1+strlen(++s)); }

方法4:利用遞歸2

int strlen(const char *s){
    if(s==NULL)    return -1;    
    return    (\0 != *s)?(1+strlen(++s):0;
}

方法5:利用中間變量2

int strlen(char s[])  
{  
  int i;  
  while (s[i] != \0)  
    ++i;  
  return i;  
}  

strlen函數實現