C语言 百分网手机站

C语言的字符串处理函数strlen()

时间:2020-10-03 08:16:07 C语言 我要投稿

C语言的字符串处理函数strlen()

  C库提供了多个字符串处理函数,ANSI C把这些函数的原型放在string.h头文件中。其中最常用的有strlen()、strcat()、strcmp()、strncmp()、strcpy()和strncpy()。另外还有sprintf(),其原型在stdio.h头文件中。下面一起来学习一下吧!

  strlen()函数

  strlen()函数用于统计字符串的长度,它会统计字符包括空格和标点符号,不统计空字符。注意与sizeof运算符区分,sizeof以字节为单位返回运算对象(变量名、类型名等)的大小。

  示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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] = '';
}</string.h></stdio.h></code>

  下面是该程序的输出:

1
2
3
4
<code>Things should be as simple as possible, but not simpler.
Things should be as simple as possible
Let's look at some more of the string.
 but not simpler.</code>

  fit()函数把第39个元素的'逗号换成了空字符。puts()函数在空字符出停止输出,并忽略其余字符。然而,这些字符还在缓冲区中,下面的函数调用把这些字符打印出来:

1
<code><code>puts(mesg + 8);</code></code>

  string.h头文件中包含了C字符串函数系列的原型,因此程序中要包含该头文件。


【C语言的字符串处理函数strlen()】相关文章:

C语言字符串处理函数10-03

C语言之字符串处理函数11-20

C语言的字符串输出puts()函数10-04

C语言的sizeof与strlen10-05

C语言字符串操作函数和常用的实现10-07

C语言中返回字符串函数的实现方法10-06

C语言函数 atoi()10-28

浅谈C语言函数10-22

C语言函数的含义10-04