字符串函数:#include<cstring>
1、字符串中都以 \0 来判断字符串结尾;
2、字符串函数中 形参(char 【】),实参(char数组或者字符串常量);
常用函数:
1、字符串拷贝:
strcpy(char 【】 a,char【】 b) 把b拷贝到a当中(若a不够长则数组越界)
2、字符串比较大小:
int strcmp(char【】 s1,char【】 s2) 返回值为int类型,0则相等,负数s1小,正数s1大
3、求字符串的长度(不算结尾的\0):
int strlen(char【】s)实际值为 sizeof(char【】s)-1
4、字符串拼接:
strcat(char【】a,char【】b)将b数组的字符串接在a数组的字符串的后面,若a数组不够长则数组越界
5、字符串换成大写:
strupr(char【】a)将a数组的字符串中的小写全换成大写
6、字符串换成小写:
strlwr(char【】b)将b数组的字符串中的大写全换成小写
字符串库函数用法eg:
#include<iostream>
#include<cstring>
using namespace std;
void printsmall(char s1[],char s2[])
{
if(strcmp(s1,s2)<=0)
cout<<s1<<endl;
else
cout<<s2<<endl;
}
int main()
{
char s1[30],s2[40],s3[100];
strcpy(s1,"hello"); //将hello拷贝给 s1
strcpy(s2,s1); //s1拷贝给s2
cout<<"1):"<<s2<<endl; //输出1):Hello
strcat(s1," word!"); //将word!拼接在s1的后面
cout<<"2):"<<s1<<endl; //输出2):hello word!
int n=strlen(s1); //计算s1中字符串的长度(不算结尾\0)
cout<<"3):"<<n<<","<<strlen("a b c")<<endl; //输出3):9,5
strupr(s1); //将s1数组中所有小写字符换成大写字符
cout<<"4):"<<s1<<endl; //输出4):HELLO WORD!
strlwr(s1); //将s1数组中所有大写字符换成小写
cout<<"5):"<<s1<<endl; //输出5):hello word
return 0;
}