C++ String 复习

今天发现自己不怎么会用C++ String

1:String的创建

string str1 ="abcd"
string str2;
str2="abcd";
//本方法调用拷贝构造函数
string str3("abcd");
string str4(4,'x');//用4个字符初始化
string str5("ILOVELUOGU",1,4);
//类似于截取

C++ string和py不同 C++是从0开始 没反向序号

2:C++string和C语言char*区别:

C++ string中有size和length函数来判断当前字符串长度

C++ string访问不能直接用printf 需要用data(),c_str()

printf("%s\t%s\n",str2.data(),str2.c_str())

3 :基本操作(增删改查)

3.1 c++string的赋值方式:

通过函数assign

#include<iostream>
#include<cstring>
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(s1);
}
#include<iostream>
#include<string>
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(s1,1,4);
}
#include<iostream>
#include<string>
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(4,'k');
}

3.2 比较

直接用运算符去比较,返回布尔类型

#include<iostream>
#include<string>
using namespace std;
int main(){
string first = "123";
string second = "23";
cout<<(first>second)<<endl;
return 0;
}

 调用成员函数

compare

#include<iostream>
#include<string>
using namespace std;
int main(){
string first = "123";
string second = "23";
cout<<first.compare(second)<<endl;
return 0;
}

3.3字符串连接

直接用加法

#include<iostream>
#include<string>
using namespace std;
int main(){
string first = "123";
string second = "23";
cout<<first+second<<endl;
return 0;
}

通过函数append(可以更灵活连接)

#include<iostream>
#include<string>
using namespace std;
int main(){
string first = "123";
string second = "23";
first.append(second);
return 0;
}

3.3 C++string查找

find:从左往右找,找子串or字符 返回string::npos(-1)

#include<iostream>
#include<string>
using namespace std;
int main(){
string findstr("Iloveyou,Imissyou");
if(findstr.find('o')!=string::npos)
    cout<<findstr.find('o')<<endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main(){
string findstr("Iloveyou,Imissyou");
if(findstr.rfind('o')!=string::npos)
    cout<<findstr.rfind('o')<<endl;
return 0;
}

find_first_of:查找第一次出现的字串

#include<iostream>
#include<string>
using namespace std;
int main(){
string findstr("Iloveyou,Imissyou");
if(findstr.find_first_of("you")!=string::npos)
    cout<<findstr.find_first_of("you")<<endl;
return 0;
}

子串:要找字符串的任意一个字符

find_first_not_of:第一次不是字串的位置

从右往左:find_last_of:功能和上面一样

3.4替换 replace

#include<iostream>
#include<string>
using namespace std;
int main(){
string r1str("Iloveyou,Imissyou");
r1str.replace(1,4,"miss");
cout<<r1str<<endl;
return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值