这里主要介绍的是使用自带库string完成的操作,大家也可以自行手动实现一下。
substr()
所在头文件
#include<string>
语法:
string substr (size_t position, size_t length);
第一个参数是起始位置(从0开始),第二个位置是持续的长度。
例子:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "Hello world!";
string substr = str.substr(0, 5);
cout << substr << endl; //输出"Hello"
substr = str.substr(6, 6);//输出“World!"
cout << substr << endl;
}
这个函数虽然好用,但是有限制,就是必须要提前知道两个参数。但是很多时候,我们无法得知字符串的长度或需要的子串的长度。比如说获取了一个文件的地址,需要在该文件的同级文件夹下再创建一个文件。这个字符串前面的路径长度是未知的,获取substr的第二个参数就存在问题。于是我们还需要用到find()函数。
find()
find函数顾名思义是查找,找的是第一个匹配到的目标位置,返回值类型是int
所在库:
#include<string>
语法:
int find(const _Elem*, const size_type off = 0)
在第一个位置写上需要查找的元素(可以是字符也可以是字符串),第二个位置是开始查找的位置(默认从0开始)。
例子:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "Hello,world,";
int end = str.find(",");
string substr = str.substr(0, end);
cout << substr << endl; //输出"Hello"
}
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "Hello,world,";
int begin = str.find(",");
int end = str.find("or");
string substr = str.substr(begin + 1, end);
cout << substr << endl; //输出"world,"
}