C指针计算字符串长度


#include <stdio.h>

int stringLength (const char *string)
{
    const char *cptr = string;

    while ( *cptr )
        ++cptr;
    return cptr - string; //cptr表示指向字符串的\0字符的位置,string表示指向字符串的第一个字符的位置,所以两者相减就是字符串的长度
}

int main (void)
{
    int stringLength (const char *string);

    printf ("%i ", stringLength ("stringLength test"));
    printf ("%i ", stringLength (""));
    printf ("%i\n", stringLength ("complete"));

    return 0;
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM