字符串库函数

字符串库函数

  • 使用字符串函数需要#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;

}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值