C語言strlen()函數用法


C語言strlen()函數:返回字符串的長度

頭文件:#include <string.h>

strlen()函數用來計算字符串的長度,其原型為:unsigned int strlen (char *s);  s為指定的字符串

eg:

#include<stdio.h>
#include<string.h>
int main()
{
    char *str1 = "http://see.xidian.edu.cn/cpp/u/shipin/";
    char str2[100] = "http://see.xidian.edu.cn/cpp/u/shipin_liming/";
    char str3[5] = "12345";
    printf("strlen(str1)=%d, sizeof(str1)=%d\n", strlen(str1), sizeof(str1));
    printf("strlen(str2)=%d, sizeof(str2)=%d\n", strlen(str2), sizeof(str2));
    printf("strlen(str3)=%d, sizeof(str3)=%d\n", strlen(str3), sizeof(str3));
    return 0;
}
運行結果:
strlen(str1)=38, sizeof(str1)=4
strlen(str1)=45, sizeof(str1)=100
strlen(str1)=53, sizeof(str1)=5

如果字符的個數等於字符數組的大小,那么strlen()的返回值就無法確定了,例如
    char str[6] = "abcxyz";
strlen(str)的返回值將是不確定的。因為str的結尾不是0,strlen()會繼續向后檢索,直到遇到'\0',而這些區域的內容是不確定的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM