字符串处理函数(新函数)

由于字符串的应用广泛,为方便用户对字符串的处理,C语言函数库中除了前面用到的库函数gets()与puts()之外,还提供了另外一些常用的库函数,其函数原型说明在string中。下面介绍一些最常用的字符串库函数。

1.函数名:strcpy

 用法:strcpy(s1,s2)

 功能:将s2复制到s1

2.函数名:strcat

 用法:strcat(s1,s2)

 功能:连接s2到s1的末尾,切s1后面的'\0'被取消

3.函数名:strlen

 用法:strlen(s1,s2)

 功能:返回s1的长度(不包含空字符)

4.函数名:strcmp

 用法:strcmp(s1,s2)

 功能:当s1=s2时,返回0值。当s1>s2时,返回大于0的值。当s1<s2时,返回小于0的值。

5.函数名:strchr

 用法:strchr(s1,ch)

 功能:返回指针,指向ch在s1中的首次出现

6.函数名:strstr

 用法:strstr(s1,s2)

 功能:返回指针,指向s2在s1中的首次出现

7.函数名:strlwr

 用法:strlwr(s)

 功能:转换s中的大写字母为小写字母

8.函数名:strupr

 用法:strupr(s)

 功能:转换s中的小写字母为大写字母

这些函数都是在string函数库中,所以当用到这些函数的时候都需要声明头文件#include <string.h>

下面是示例,由于还没学到指针章节,所以目前只能理解前面4个函数。

//1.strcpy函数与strcat函数
#include <stdio.h>
#include <string.h>
int main()
{
    char buffer[80];            //buffer数组作为缓冲数组。
    strcpy(buffer,"hello");     //把“hello”复制给buffer数组。
    strcat(buffer," world!");   //把“ world”连接到buffer数组的后面。
    printf("%s",buffer);
}
//2.strlen函数与strcmp函数
#include <stdio.h>
#include <string.h>
int main()
{
    char buf1[]="aaa",buf2[]="bbb",buf3[]="ccc";
    int buf;
    printf("buf1的长度为:%d\n",strlen(buf1));
    buf=strcmp(buf1,buf2);
    if(buf>0)
        printf("buf1 is greate than buf2.\n");
    else
        printf("buf1 is less than buf2.\n");
    buf=strcmp(buf2,buf3);
    if(buf>0)
        printf("buf2 is greate than buf3.\n");
    else
        printf("buf2 is less than buf3\n");
}

猜你喜欢

转载自www.cnblogs.com/yhc99/p/9161929.html