String容器C++

// 创建String

#include<string>

string str;
string str2 = "abc";
str = str2;

string str3(6, "a"); // str3="aaaaaa"

string str4 = "abcde"

string str5;

str5.assgin(str4, 3); // str5 = "abc"

string str6;

str6.assgin(str4, 2, 3) // str6 = "cde"
// string中括号和at的访问区别

string str = "hello world";

for(int i = 0 ; i< str.size(); i++){
    
    cout << str[i] <<endl;

    cout << str.at(i) <<endl;
}

// [] 和 at 区别:[]当越界时直接宕机,at越界时抛出异常

#include<stdexcept>

try{
    cout << str[1000] << endl;
}
catch(out_of_range& e)
{
    cout << e.what() <<endl;
}
catch(...) // 当不知道什么异常时可用...代替
{
    cout << "越界错误" <<endl;
}
// string 中的 append find 和replace
#include<string>

string str = "abc";

string str2 = "def";

string str3 = str+str2; // abcdef

string str4 = str3.append("ghi") //abcdefghi

int pos = str4.find("cde")

cout << pos <<endl;  // pos = 2

int pos2  = str4.find("cdf") // pos2 = -1

str4.replace(1, 4, "我爱你“)

cout << str4 <<endl; // str4 = "a我爱你fghi"

 

// string compare

string str3 = "abc";
string str4 = "bcd";

if(str3.compare(str4) == 0) {
    
    cout << "str3等于str4" << endl;

}else if(str3.compare(str4) == 1) {

    cout << "str3大于str4" << endl;

}else{
    
    cout << "str3小于str4" <<endl;

}


// string 子串

string str5 = str3.substr(0,2)

cout <<str5 <<endl; // "ab"


str3.insert(1,"111"); //str3 = "a111bc";

str3.erase(1,3); //str3 = "abc";

// const char * 可以隐式转换为string

// string 不可以隐式转换为 const char*

 

// string再被重新赋值后,如果长度比原来的更加长了,那么会被重新分配内存,地址也改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_37539225

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值