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

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

在这里插入图片描述

C库提供了多个字符串处理函数,ANSI C把这些函数的原型放在string.h头文件中。其中最常用的有strlen()、strcat()、strcmp()、strncmp()、strcpy()和strncpy()。另外还有sprintf(),其原型在stdio.h头文件中。这些函数都在后面的博客进行详细分析。

strlen()函数

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

示例:

/* 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] = '\0';
}

下面是该程序的输出:

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.

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

puts(mesg + 8);

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Galaxy_Robot

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值