栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ String 复习

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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("%st%sn",str2.data(),str2.c_str())
3 :基本操作(增删改查)

3.1 c++string的赋值方式:

通过函数assign

#include
#include
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(s1);
}
#include
#include
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(s1,1,4);
}
#include
#include
using namespace std;
int main(){
string s1("IMISSYOU");
string s2;
s2.assign(4,'k');
}
3.2 比较

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

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

 调用成员函数

compare

#include
#include
using namespace std;
int main(){
string first = "123";
string second = "23";
cout< 
3.3字符串连接 

直接用加法

#include
#include
using namespace std;
int main(){
string first = "123";
string second = "23";
cout< 

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

#include
#include
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
#include
using namespace std;
int main(){
string findstr("Iloveyou,Imissyou");
if(findstr.find('o')!=string::npos)
    cout< 
#include
#include
using namespace std;
int main(){
string findstr("Iloveyou,Imissyou");
if(findstr.rfind('o')!=string::npos)
    cout< 

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

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

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

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

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

3.4替换 replace
#include
#include
using namespace std;
int main(){
string r1str("Iloveyou,Imissyou");
r1str.replace(1,4,"miss");
cout< 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/744011.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号