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