几种常用的字符串处理函数

1.puts函数(字符串输出函数)

一般形式:puts(字符数组)

作用:输出一个字符串(以‘\0’结束的字符序列)。

2.gets函数(字符串输入函数)

一般形式:gets(字符数组)

作用:从终端输入一个字符串到字符数组函数。
#include <stdio.h>
int main()
{
    char s[100];
    gets(s);
    puts(s);
    return 0;
}

3.strcat(字符串连接函数)

一般形式(字符数组1,字符数组2)

作用:把两个字符数组中的字符串连接起来(字符串1在前,字符串2在后)。结果放在字符数组1中。
#include <stdio.h>
#include <string.h>
int main()
{
    char s1[100]="Hello";
    char s2[100]="World";
    strcat(s1,s2);
    printf("%s\n%s\n",s1,s2);
    return 0;
}

4.strcpy,strncpy(字符串复制函数)

①strcpy

一般形式:strcpy(字符数组1,字符串2)

作用:将字符串2复制到字符数组1中。

②strncpy

一般形式:strncpy(字符数组1,字符串2,n(字符个数))

作用:将字符串2中前n个字符复制到字符数组1中。
#include <stdio.h>
#include <string.h>
int main()
{
    char s1[100]="Hello World";
    char s2[100];
    strcpy(s2,s1);
    printf("%s\n",s2);
    memset(s2,'\0',sizeof(s2)); // 重置s2
    strncpy(s2,s1,5);
    printf("%s\n",s2);
    return 0;
}

5.strcmp(字符串比较函数)

一般形式:strcmp(字符串1,字符串2)

作用:比较字符串1和字符串2。

规则:将两个字符串中的字符从左至右逐个相比(按ASCII码大小相比),直到出现不同的字符或遇到'\0'为止。

比较结果由函数值带回:

    (1)字符串1=字符串2,函数值为0。

    (2)字符串1>字符串2,函数值为一个正整数。

    (3)字符串1<字符串2,函数值为一个负整数。

6.strlen

一般形式:strlen(字符数组)

测量字符串的实际长度。(不包括'\0')

7.strlwr(转化为小写的函数)

一般形式:strlwr(字符串)

作用:将字符串中的大写字母转化为小写。

8.strupr(转化为大写的函数)

一般形式:strupy(字符串)

作用:将字符串中的小写字母转化为大写字母。

猜你喜欢

转载自blog.csdn.net/huang1600301017/article/details/85323478