// txj.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include<string>
using namespace std;
int main()
{
1:定义和初始化string对象
string s1;
string s2 = "I LOVE CHINA";
string s3("I LOVE CHINA");
string s4 = s2;//s2的内容拷贝到s4中,不包括'\0'
int num = 10;
string s5(num,'b');//s5为"bbbbbbbbbb"
char str[10] = "hfjka";
string s6(str);//用字符数组初始化
2:string对象的操作
(1)empty()
string s1;
if (s1.empty())//判断是否为空,返回布尔值
{
cout << "s1为空" << endl;
}
string s2 = "I LOVE CHINA";
//(2)size() length()
if (s2.size() > 4)
{
cout << s2.size() << endl;//返回字符串字节个数
cout << s2.length() << endl;
}
string s3 = "我爱中国";//一个汉字两个字节
cout << s3.size() << endl;
cout << s3.length() << endl;
//(3) s[n]
//s[n] 返回字符串的n个位置的下标,从0到n减一
cout << s2[4] << endl;
s2[4]='k';//更改下标的值
cout << s2 << endl;
string s4 = s3;//字符串赋值
string s5;
//(4)相等与不相等
if (s5 == s4)//判断两个字符串是否相等,大小写敏感
{
cout << "s5==s4" << endl;
}
if (s5 != s4)//判断两个字符串不相等
{
cout << "s5!=s4" << endl;
}
//(6).c_str()
string s6 = "abcd";
const char* p = s6.c_str();//返回一个常量指针.c_str()由于c没有string类型,目的是为了与c中的字符串兼容
char str[10];
strcpy_s(str, sizeof(str), p);
cout << str << endl;
//(7)读写string对象
//string s7;
//cin >> s7; //输入 abc lkl 输出abc,截掉前面的空格
//(8)string类对象相加
string s7="asfas";
string s8="fsdf";
string s9=s8+s7;
cout << s9 << endl;
s9 = s7 + "fas" + s8;
cout << s9 << endl;
//s9 = "asklfjkl" + "asdn"; 不可以,系统为再左结合性,一开始就相加两个字符串,系统是不知道他们的类型的
s9 = "asklfjkl" + s7 + "asdn";//可以
//(9)范围for语句在string中的使用,c++11(范围for语句)
for (auto c : s7)//auto自动推动c的类型
{
cout << c << endl;//遍历s7
}
for (auto &c : s7)//auto自动推动c的类型 加引用可以修改s7里面的内容
{
c = toupper(c);//转换为大写字符
}
cout << s7 << endl;
return 0;
}
c++ string类对象的使用
最新推荐文章于 2022-07-27 21:41:48 发布