欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

string.h(cstring)函数库学习笔记

程序员文章站 2022-07-09 22:55:23
...

字符串类库,非常实用的一个库,里面的一些函数操作可以省掉很多比较麻烦的实现。下面来一一说明。

(1)strcpy
字符串复制函数,原型是:

char *strcpy(char* dest, const char *src);

很明显的就是将src的内容给了dest,例如:

#include <string.h>
int main()
{
    char a[50]="this is a string.";
    char b[50]="this is another string.";
    strcpy(b,a);
    puts(b);
    char c[50];
    strcpy(c,"Successful!");
    puts(c);
    return 0;
}

运行结果:

this is a string.
Successful!

(2)strcmp

字符串比较函数,原型如下:

extern int strcmp(const char *s1,const char *s2);

作用就是比较s1和s2的大小关系,需要注意的是,这里比较的是两个字符串之间的对应ascii码值的字典序大小,和字符串的长度没有关系,返回的结果是两个字符串的相对大小关系,如果s1

#include <cstring>
int main()
{
    char a[50]="this is a string.";
    char b[50]="this is another string.";
    char c[50]="this is another string.";
    char d[50]="this is d.";
    printf("%d\n",strcmp(a,b));//a<b
    printf("%d\n",strcmp(b,c));//b==c
    printf("%d\n",strcmp(d,a));//d>a
    return 0;
}

运行结果:

-1
0
1

(3)strchr

字符查找函数,原型是:

extern char *strchr(const char *s,char c);

用来查找字符c是否在字符串s中出现过,如果出现过就返回在s中首次出现的地址,如果没有出现过就返回NULL。例如:

#include <cstring>
int main()
{
    char a[50]="asdfghjkl";
    char *b;
    for(char x='a';x<='z';x++)
    {
        b=strchr(a,x);
        if(b!=NULL)
            printf("%c is found at %d\n",x,b-a);//b-a表示返回该字符在字符串中首次出现的下标
        else
            printf("%c is not found\n",x);
    }
    return 0;
}

运行结果:

a is found at 0
b is not found
c is not found
d is found at 2
e is not found
f is found at 3
g is found at 4
h is found at 5
i is not found
j is found at 6
k is found at 7
l is found at 8
m is not found
n is not found
o is not found
p is not found
q is not found
r is not found
s is found at 1
t is not found
u is not found
v is not found
w is not found
x is not found
y is not found
z is not found

(4)strstr
字符串查找函数,函数原型:

extern char *strstr(char *str1, const char *str2);

作用是在str1中查找str2,看看str2是不是str1的子串,如果是的话就返回第一次出现的地址,否则就返回NULL。例如:

#include <stdio.h>
#include <string.h>

int main()
{
    char a[50]="this is a string";
    char b[50]="this";
    char c[50]="string";
    char d[50]="substring";
    if(strstr(a,b)!=NULL)
        printf("\'%s\' is the substring of \'%s\'\n",b,a);
    else
        printf("\'%s\' is not the substring of \'%s\'\n",b,a);
    if(strstr(a,c)!=NULL)
        printf("\'%s\' is the substring of \'%s\'\n",c,a);
    else
        printf("\'%s\' is not the substring of \'%s\'\n",c,a);
    if(strstr(a,d)!=NULL)
        printf("\'%s\' is the substring of \'%s\'\n",d,a);
    else
        printf("\'%s\' is not the substring of \'%s\'\n",d,a);
    return 0;
}

运行结果:

'this' is the substring of 'this is a string'
'string' is the substring of 'this is a string'
'substring' is not the substring of 'this is a string'