C++学习笔记:字符串

C++ 提供了以下两种类型的字符串表示形式:

  • C 风格字符串
  • C++ 引入的 string 类类型

C风格字符串

//C风格字符串:一维字符型数组 以NULL或'\0'终止 
#include<iostream>
#include<cstring>//使用字符串函数需要引入头文件 cstring或string.h 

using namespace std;

int main(){
	
	char arr[10]="hello";
	char brr[10]="worldhhh";
	char crr[10];
	int len,k;
	
	strcpy(crr,brr);//把brr复制到arr中 
	cout<<"strcpy(crr,brr):"<<crr<<endl;
	
	strcat(arr,brr);//连接arr和brr:把brr接到arr后面 
	cout<<"strcat(arr,brr):"<<arr<<endl;
	
	len=strlen(arr);//arr的长度 
	cout<<"strlen(arr):"<<len<<endl;
	
	k=strcmp(arr,brr);//比较两个字符串的大小:arr>brr返回大于0,相等0,否则小于0(-1) 
	cout<<"strcmp(arr,brr):"<<k<<endl;	
	
	return 0;
}

输出结果为:

strcpy(crr,brr):worldhhh
strcat(arr,brr):helloworldhhh
strlen(arr):13
strcmp(arr,brr):-1

C++引入的string类类型

理解面向对象的概念,类和实例:创建string类的实例s1,s2,s3

//C++字符串类
//头文件 string
#include<iostream>
#include<string>

using namespace std;

int main(){
	
	string s1="hello";//变量类型为string 
	string s2="worldhhh";
	string s3;
	int len;
	bool k;
	
	s3=s1;//把s1复制到s3中
	cout<<"s3:"<<s3<<endl;
	
	s3=s1+s2;//连接s1 s2
	cout<<"s3:"<<s3<<endl;
	
	len=s3.size();//方法:返回字符串的长度 
	cout<<"s3.size():"<<len<<endl;
	
	k=s1>s2;//直接比较两个字符串大小:0为false 1为true
	cout<<"s1>s2:"<<k<<endl; 
	return 0;
} 

输出结果为:

s3:hello
s3:helloworldhhh
s3.size():13
s1>s2:0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值