C语言的字符串处理函数strlen()
- C语言
- 关注:3.78K次
C库提供了多个字符串处理函数,ANSI C把这些函数的原型放在string.h头文件中。其中最常用的有strlen()、strcat()、strcmp()、strncmp()、strcpy()和strncpy()。另外还有sprintf(),其原型在stdio.h头文件中。下面一起来学习一下吧!
strlen()函数
strlen()函数用于统计字符串的长度,它会统计字符包括空格和标点符号,不统计空字符 。注意与sizeof运算符区分,sizeof以字节为单位返回运算对象(变量名、类型名等)的大小。
示例:
123456789101112131415161718192021222324 | <code> /* test_fit.c -- try the string-shrinking function */ #include <stdio.h> #include <string.h> /* contains string function prototypes */ void fit( char *, unsigned int ); int main( void ) {
char mesg[] = "Things should be as simple as possible,"
" but not simpler." ;
puts(mesg);
fit(mesg, 38 );
puts(mesg);
puts( "Let's look at some more of the string." );
puts(mesg + 39 );
return 0 ; } void fit( char *string, unsigned int size) {
if (strlen(string) > size)
string[size] = ' |