Loading... 前言:由于自己一味追求进度,导致字符串函数并是太熟练使用,于是我来小补一节 首先这是c语言编译系统提供的函数,所以必须在开头须写上: **#include <string.h>** ## puts(字符数组)函数----输出字符串的函数 作用:将一个字符串(以‘\0’结束的字符序列)输出到终端。 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[]="bendangmi"; puts (a); } ``` ## gets(字符数组)函数----输入字符串函数 作用:从终端输入一个字符串到字符数组 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[20]; gets(a);//输入字符串给字符数组 puts(a);//从数组中输出字符串 } ``` <div color ="red">注意使用:gets()或puts()函数只能输入或输出一个字符串<div\> ## strcat(字符数组1,字符数组2)----字符串连接函数 作用:把字符串2接到字符串1的后面,结果放在字符数组1中(字符数组1必须足够大,以便容纳连接后的新字符串) 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "bendangmi"; char b[] = "love"; printf ("%s", strcat(b, a)); } ``` ## strcpy(字符数值1,字符数值2)----字符串复制函数 作用:将字符串2复制到字符数组1中去 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "bendangmi"; char b[20] ; printf ("%s", strcpy(b, a)); } ``` ## strcmp(字符串1,字符串2)----字符串比较函数 作用:比较字符串1与字符串2(将两个字符串自左向右逐个按ASCII码比较大小),直至出现‘\0’或遇到不同的字符 比较原则: 1. 如果字符串1与字符串2相同,则函数值为0 2. 如果字符串1>字符串2,则函数值>0 (返回一个正整数) 3. 如果字符串1<字符串2,则函数值<0(返回一个负整数) 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "bendangmi"; char b[] = "boke"; char c[] = "boke" ; char d[] = "bendangmilove"; if (strcmp (b, a) > 0) { printf ("1\n"); } if (strcmp (b, c) == 0) { printf ("2\n"); } if (strcmp (a, d) < 0) { printf ("3\n"); } } ``` ## strlen(字符数组)----测定字符串长度的函数 作用:测定字符串的实际长度 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "lovebendangmi"; printf ("%d", strlen(a)); } ``` ## strlwr(字符串)----转换为小写的函数 作用:将字符串中大写字母转换为小写字母 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "LOVEBENDANGMI"; printf ("%s", strlwr(a)); } ``` ## strupr(字符串)----转换为大写的函数 作用:将字符串中小写字母转换为大写字母 案例: ```cpp #include<stdio.h> #include<string.h> int main () { char a[] = "lovebendangmi"; printf ("%s", strupr(a)); } ``` 最后修改:2021 年 05 月 31 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果文章有用,请随意打赏。