字符串库函数
- 使用字符串函数需要#include<cstring>
- 字符串函数都根据'\0'来判断字符串结尾
- 形参为char[]类型,则实参可以是char数组或字符串常量
字符串拷贝
strcpy(char [ ] dest,char [ ] src);//拷贝src到dest
字符串比较大小
int strcmp(char [ ] s1,char [ ] s2);// 返回0则相等
求字符串长度
int strlen(char [ ] s);//不算结尾的‘/0’
字符串拼接
strcat (char [ ] s1,char [ ] s2);//s2拼接到s1后面
字符串转成大写
strupr(char [ ]);
字符串转成小写
strlwr(char [ ]);
字符串库函数用法示例
#include<iostream>
#include<cstring>//要使用字符串库函数需要包含此头文件
using namespace std;
void PrintSmall(char s1[],char s2[])//输出词典序小的字符串
{
if(strcmp(s1,s2)<=0)//如果s1<=s2
cout<<s1;
else
cout<<s2;
}
int main (){
char s1[30];
char s2[40];
char s3[100];
strcpy(s1,"Hello");//拷贝“Hello”到s1,s1=“Hello”
strcpy(s2,s1);//拷贝s1到s2,s2=“Hello”
cout<<"1)"<<s2<<endl;//输出1)Hello
strcat(s1,",world");//链接“world”到s1尾部。s1=“Hello,world”
cout<<"2)"<<s1<<endl;//输出2)Hello,world
cout<<"3)"; PrintSmall("abc",s2); cout<<endl;//输出3)Hello
cout<<"4)"; PrintSmall("abc","aaa"); cout<<endl;//输出4)aaa
int n=strlen(s2);//求s2长度
cout<<"5)"<<n<<","<<strlen("abc")<<endl;//输出5) 5,3
strupr(s1);//把s1变成大写,s1=“HELLO WORLD"
cout<<"6)"<<s1<<endl;//输出6)HELLO, WORLD
return 0;
}
strlen常见的糟糕用法
char s[100]= "test";
for (int i=0;i<=strlen(s);++i){
s[i]=s[i]+1;
}
strlen函数的执行是需要时间的,且时间和字符串的长度成正比
每次循环,都调用strlen函数,这是效率上的很大浪费
应取出s的长度存放在一个变量里面,然后在循环的时候使用该变量
char s[100]= "test";
int len=strlen(s);
for (int i=0;i<len;++i){
s[i]=s[i]+1;
}
或:
char s[100]= "test";
for (int i=0;s[i];++i) {
s[i]=s[i]+1;
}