一、前言
int,float,char,C++标准库提供的类型:string,vector。
string:可变长字符串的处理;vector一种集合或者容器的概念。
二、string类型简介
C++标准库中的类型,代表一个可变长的字符串
char str[100] = “I Love China”; // C语言用法
三、定义和初始化string对象
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 默认初始化,s1=””,””空串,表示里面没有字符
string s1;
// 把I Love China 这个字符串内容
//拷贝到了s2代表的一段内存中,拷贝时不包括末尾的\0;
string s2 = “I Love China”;
// 与s2的效果一样。
string s3(“I Love China”);
// 将s2中的内容拷贝到s4所代表的的一段内存中。
string s4 = s2;
int num = 6;
// 将s5初始化为连续num个字符的’a’,
//组成的字符串,这种方式不太推荐,
//因为会在系统内部创建临时对象。
string s5 = (num,’a’);
return 0;
}
四、string对象上的操作
(1)判断是否为空empty(),返回的布尔值
string s1;
if(s1.empty()) // 成立
{
cout << “s1字符串为空” <<endl;
}
(2)size()/length():返回字节/字符数量,代表该字符串的长度。
string s1;
cout << s1.size() << endl; // 0
cout << s1.length() << endl; // 0
string s2 = “我爱中国”;
cout << s2.size() << endl;// 8
cout << s2.length() << endl; // 8
string s3 = “I Love China”;
cout << s3.size() << endl;// 12
cout << s3.length() << endl; // 12
(3)s[n]:返回s中的第n个字符,(n是个整型值),n代表的是一个位置,位置从0开始,到size()-1;
如果用下标n超过这个范围的内容,或者本来是一个空字符串,你用s[n]去访问,都会产生不可预测的作用。
string s3 = “I Love China”;
if(s3.size()>4)
{
cout << s3[4] << endl;
s3[4] = ‘2’;
}
cout << s3 << endl; // I Lowe China
(4)s1+s2:字符串的连接,返回连接之后结果,其实就是得到一个新的string对象。
string s4 = “abcd”;
string s5 = “efgk”
string s6 = s4 + s5;
cout << s6 <<endl;
(5)s1 = s2:字符串对象赋值,用s2中的内容取代s1中的内容
string s4 = “abcd”;
string s5 = “efgk”
s5 = s4;
cout << s5 <<endl; // abcd
(6)s1 == s2:判断两个字符串是否相等。大小写敏感:也就是大小写字符跟小写字符是两个不同的字符。相等:长度相同,字符全相同。
string s4 = “abcd”;
string s5 = “abcd”
if(s5 == s4)
{
cout << “s4 == s5” <<endl; // abcd
}
(7)s1 != s2:判断两个字符串是否不相等
string s4 = “abcd”;
string s5 = “abcD”
if(s5 != s4)
{
cout << “s4 != s5” <<endl; // abcd
}
(8)s.c_str():返回一个字符串s中的内容指针,返回一个指向正规C字符串的指针常亮,也就是以\0存储。
这个函数的引入是为了与C语言兼容,在C语言中没有string类型,所以我们需要通过string对象的c_str()成员函数将string对象转换为C语言的字符串样式。
string s4 = “abcd”;
const char *p = s4.c_str(); // abcd
char str[100];
strcpy_s(str,sizeof(str),p);
cout << str << endl;
string s11(str); // 用C语言的字符串数组初始化string类型。
(9)读写string对象
string s1;
cin >> s1; // 从键盘输入
cout << s1 << endl;
(10)字面值和string相加
string str1 = “abc”;
string str2 = “def”;
string str3 = s1 + “ and ” + s2 + ‘e’; // 隐式类型转换
cout << str3 << endl; // abc and defe;
// string s1 = “abc” + “def”; // 语法上不允许
(11)范围for针对string的使用:C++11提供了范围for:能够遍历一个序列的每一个元素。string可以看成一个字符序列。
string s1 = “I Love China”;
for(auto c:s1) // auto:变量类型自动推断
{
cout << c << endl; // 每次输出一个字符,换行
}
for(auto &c:s1) // auto:变量类型自动推断
{
// toupper()把小写字符转换为大写,大写字符不变
c = toupper(c); // 因为c是一个引用,所以这相当于改变s1中的值
}
cout << s1 << endl;
好了,今天的C++学到这里就结束了,喜欢的朋友可以给我点个赞哦!!!
网友评论