清溪镇网站建设,wordpress权限数字,新网域名搭建网站,模板做网站多少钱字符串库函数
使用字符串函数需要#includecstring字符串函数都根据\0来判断字符串结尾形参为char[]类型#xff0c;则实参可以是char数组或字符串常量
字符串拷贝
strcpy(char [ ] dest,char [ ] src);//拷贝src到dest
字符串比较大小
int strcmp(char [ ] s1,ch…字符串库函数
使用字符串函数需要#includecstring字符串函数都根据\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后面
字符串转成大写
struprchar [ ];
字符串转成小写
strlwrchar [ ];
字符串库函数用法示例
#includeiostream
#includecstring//要使用字符串库函数需要包含此头文件
using namespace std;
void PrintSmall(char s1[],char s2[])//输出词典序小的字符串
{if(strcmp(s1,s2)0)//如果s1s2couts1;elsecouts2; }int main (){char s1[30];char s2[40];char s3[100];strcpy(s1,Hello);//拷贝“Hello”到s1s1“Hello”strcpy(s2,s1);//拷贝s1到s2s2“Hello”cout1)s2endl;//输出1Hellostrcat(s1,,world);//链接“world”到s1尾部。s1“Helloworld”cout2)s1endl;//输出2Helloworldcout3); PrintSmall(abc,s2); coutendl;//输出3Hellocout4); PrintSmall(abc,aaa); coutendl;//输出4aaaint nstrlen(s2);//求s2长度cout5)n,strlen(abc)endl;//输出5 5,3strupr(s1);//把s1变成大写s1“HELLO WORLDcout6)s1endl;//输出6HELLO, WORLDreturn 0; }
strlen常见的糟糕用法
char s[100] test;
for (int i0;istrlen(s);i){ s[i]s[i]1;
}
strlen函数的执行是需要时间的且时间和字符串的长度成正比
每次循环都调用strlen函数这是效率上的很大浪费
应取出s的长度存放在一个变量里面然后在循环的时候使用该变量
char s[100] test;
int lenstrlen(s);
for (int i0;ilen;i){ s[i]s[i]1;
}
或
char s[100] test;
for (int i0;s[i];i) { s[i]s[i]1;
}