string类中存在find()和rfind(),即为正向查找和反向查找
下面的实操中,我们都以正向查找为例为大家演示效果
#include <iostream>
#include<string>
#include<Windows.h>
using namespace std;
//分别取域名和协议名
string GetDmain(const string& url)
{
size_t pos = url.find("://"); //找到“://”返回的是“:”的位置
if (pos != string::npos)
{
size_t start = pos + 3; //找到域名的起始位置
size_t end = url.find("/", start); //此处找到的是域名的结束位置的下一个位置
if (end != string::npos)
{
return url.substr(start, end-start); //左闭右开所以直接相减算出域名长度,再从起始位置取出
}
else
{
return string();
}
}
else
{
return string();
return 0;
}
}
string GetProtocal(const string& url)
{
size_t pos = url.find("://");
if (pos != string::npos)
{
return url.substr(0, pos - 0);
}
else
{
return string(); //返回的是一个匿名对象
}
}
int main()
{
//假设要求取文件名后缀
string filename = "test.cpp";
size_t pos = filename.find(".");
if (pos != string::npos)
{
string suff(filename, pos);
cout << suff << endl;
}
string url = "https://mp.csdn.net/mp_blog/manage/article?spm=1010.2135.3001.5416";
cout << GetDmain(url) << endl;
cout << GetProtocal(url)<< endl;
system("pause");
return 0;
}
运行结果:分别为去后缀,取网络域名,取协议名