1.​​compare​​函数

1.1 功能

比较两个字符串,如果相同则返回0;如果不同则返回-1

1.2 代码

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

int main(){
string str1 = "abc";
string str2 = "abc";
string str3 = "abd";
cout << str1.compare(str2) << "\n";
cout << str1.compare(str3) << "\n";
}

1.3 执行结果

C++中 string 常用的函数_字符串

2. ​​substr()​​函数的使用

2.1 功能


  • ​substr(int index)​​返回的是字符串从下标index开始,到字符串末尾的一个子串
  • ​substr(int start,int len)​​​ 从 ​​start​​​ 处开始,返回一个长度为 ​​len​​的字符串

2.2 代码

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

int main(){
string str1 = "Push 309";
cout << str1 << "\n";
cout << str1.substr(5);
}

2.3 执行结果

C++中 string 常用的函数_ios_02

3.添加字符

在C++中,如果要在一个字符串后添加一个字符,可以直接使用​​+=​​即可。示例如下。

3.1 代码

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

int main(){
string res ="My ";
res+= "n";
res+= "a";
res+= "m";
res+= "e";

res+= " is LittleLawson!";
cout << res;
}

3.2 执行结果

C++中 string 常用的函数_#include_03

4.查找字符串

在主串中找出子串的位置。可以使用find()函数。


  • 成功查找时:find()函数返回的是第一次匹配成功的主串起始下标。
  • 查找失败:返回npos

4.1 代码

#include<iostream>
#include<vector>
#include<string>
using namespace std;

//字符串查找
void test1(){
string str1 = "law",str2 = "salawsonlaw";
string::size_type idx;

//在str2串中找str1串
cout << str2.find(str1)<<"\n";
idx = str2.find(str1);

//如果找不到,则返回npos(这个是string字符串中的一个特殊标记)
if(idx == string::npos){
cout <<"not found";
}
else//否则返回 第一次 匹配的下标
cout << idx;
}

int main(){
test1() ;
return 0;
}

5.替换字符串

如何实现字符串的替换?

可以 使用​​replace(int index,int len,string str1)​​函数。其功能是将主串中从下标index开始,长度为len的字符串替换为str1。

5.1代码

#include<iostream>
#include<vector>
#include<string>
using namespace std;

//字符串替换
void test2(){
string str2 = "salawson_t";
string ans;//如果能找到相同串,则替换

//将 下标从0开始,长度为2的字符串 替换为""
str2.replace(0,2,"");
cout << str2 <<"\n";
}

int main(){
test2();
return 0;
}

5.2执行结果

C++中 string 常用的函数_c++_04