用STL进行字符串的分割与合并

涉及到string类的两个函数find和substr:

1、find函数
        原型:       size_t find ( const string& str, size_t pos = 0 ) const;
        功能:       查找子字符串第一次出现的位置。
        参数说明:str为子字符串,pos为初始查找位置。
        返回值:    找到的话返回第一次出现的位置,否则返回string::npos
2、substr函数
        原型:       string substr ( size_t pos = 0, size_t n = npos ) const;
        功能:       获得子字符串。
        参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
        返回值:    子字符串

#include <iostream>
#include <string>
#include <vector>
 
//字符串分割函数
std::vector<std::string> split(std::string str,std::string pattern)
{
    std::string::size_type pos;
    std::vector<std::string> result;
    
    str+=pattern;//扩展字符串以方便操作
    int size=str.size();
    
    for(int i=0; i<size; i++)
    {
        pos=str.find(pattern,i);
        if(pos<size)
        {
            std::string s=str.substr(i,pos-i);
            result.push_back(s);
            i=pos+pattern.size()-1;
        }
    }
    return result;
}
 

分割:

int main()
{
    std::string str = "C:/Users/EHome_LJG/Desktop/images/3.jpg";
	std::string pattern = "/.";

    std::vector<std::string> result=split(str,pattern);
    std::cout<<"The result:"<<std::endl;
    for(int i=0; i<result.size(); i++)
    {
        std::cout<<result[i]<<std::endl;
    }
    
    return 0;
}

合并:

void main()
{
	std::string str = "C:/Users/EHome_LJG/Desktop/images/3.jpg";
	std::string pattern = "/.";
	std::vector<std::string> result = split(str, pattern);
	int pos = 0;
	for (int i = 0; i < result.size(); i++)
	{
		if (result[i] == "jpg")
		{
			pos = i;
		}
	}
	std::string strs;
	for (int i = 0; i < pos - 1; i++)
	{
		strs += result[i] + "/";
	}

	cout << strs << endl;

}

参考链接:

https://blog.csdn.net/freeking101/article/details/55505399

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LoveWeeknd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值