1、string简介
string是用来处理可变长字符用的,vector是一种集合、容器或者动态数组的概念。
string类型是一个标准库中的类型,代表一个可变长字符串。
string也位于std 命名空间中。所以,要使用string类型.cpp 源文件前面也增加 using namespace std 代码行,后续就可以直接使用string类型,如果不加这行代码,每次都要使用stdstring的形式,比较麻烦。
2、string 对象上的常用操作
(1)判断是否为空empty(),返回布尔值。
- int main()
- {
- string str;
- if (str.empty())//为真
- {
- cout << "str is null!" << endl;
- }
- return 0;
- }
(2)size()或者length():返回字节/字节数量,可以理解成返回的是一个无符号数,unsigned int。
- string str1;
- cout << str.size() << endl; //0
- cout << str.length() << endl;//0
- string str2;
- str2 = "jinxueHou";
- cout << str2.size() << endl;//9
- cout << str2.length() << endl;//9
(3)s[n]:返回s中的第n字符(n是一个整型值) 字符位置从0开始计算,位置值n也必须小于.size(),如果用下标引用超过这个范围,或者用下标访问一个""的string,都会产生不可预测的结果。
- string s3 = "I love China";
- if (s3.size() > 4)
- {
- cout << s3[4] << endl; //打印'v'
- s3[4] = 'V';
- }
- cout << s3 << endl; //I loVe China
(4)s1 + s2 ,字符串连接,返回连接后的结果,其实就是得到一个新string对象。
- string s1 = "I love you";
- string s2 = " my motherland";
- string s3 = s1+s2; //s3=“I love you my motherland”
- cout << s3 << endl;
(5)s1 = s2:字符串对象赋值,用s2里面的内容取代原来s1里面的内容。
- string s1 = "I love you";
- string s2 = " my motherland";
- s1 = s2;//s1 = " my motherland";
(6)s1 == s2:判断两个字符串是否相等{长度相同,字符也全相同) 大小写敏感,也就是大写字符与小写字符是两个不同的字符。
- string s1 = "abc";
- string s2 = "abc";
- if(s1 == s2)//条件成立
- {
- cout << "s1==s2" << endl;
- }
如果把s1或者s2字符串中的某个字符改为大写,则条件就不成立了。
(7)s1 != s2:判断两个字符串是否不相等。
- string s1 = "abc";
- string s2 = "Abc";
- if(s1 != s2)//条件成立
- {
- cout << "s1!=s2" << endl;
- }
(8)s.c_str():返回一个字符取s中的内容指针(也就是说这个内容实际上就是 stnng 字符串里的 内容),返回的是一个指向正规C符串的常量指针,所以是以‘\0’结尾的.
这个函数是为了与C语言兼容,在C语言中没有string 类型,所以得通过string类对象的成员函数c_str把string对象转换成C中的字符串样式。
- string s2 = "abcdefgh";
- const char* p = s2.c_str();
- char str[100];
- strcpy_s(str,sizeof(str),p);//字符串内容复制到str
- cout << str << endl;//"abcdefgh\0";
- cout << strlen(str) << endl;//打印实际字符串内容长度:8个字节
(9)读写string对象。
- string s1;
-
- cin >> s1; //输入123回车
- cout << s1 << endl; //输出123字符串
(10)字面值和 string 相加。
- string s1 = "abc";
- string s2 = "defg";
- string s3 = "and"+s2+'e';
- cout << s3 << endl;
以后讲解类的时候会讲到隐式类型转换,实际上在这里”and”和 'e' (字符串和单个字符〉都被转换成了string对象参与加法运算。
但有一点还是要注意一下:
- string s1 = "abc";
- string s2 = "defgh";
- string s3 = "abc" + "defgh";//语法上不允许,会报错
- string s4 = "abc" + s1 + "def";//中间夹杂一个string对象,语法上允许
- string s5 = "abc"” + "defgh" + s2;//报错,两个字符串不能紧挨着
(11)范围for针对string的使用。
- string s1 = "I love China";
- for (auto &c : s1)//c的类型是字符char
- {
- cout << c << endl;
- }
把小写字符串转为大写字符串:
- int main()
- {
- string s1 = "I love China";
- for (auto& c : s1)
- {
- c = toupper(c);
- }
- cout << s1 << endl;
-
- return 0;
- }
到此,字符串string的常用操作说明已完成。
2022.06.25结。