C++ 字符串

本文介绍了多种字符串操作的方法,包括如何使用substr进行截取、find_last_of查找特定字符最后一次出现的位置、strrchr及strchr分别用于获取字符串中指定字符最后一次及第一次出现的位置之后的部分,同时还展示了如何利用boost库进行字符串分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串截取

string str = "012345";

//从第0位开始截取3个
string str1 = str.substr(0,3)  //012

//获取字符串的最后一位
string str2 = str.substr(str.length()-1,1)  //5

https://www.cnblogs.com/komean/p/11109555.html

s.find(s1)
https://blog.youkuaiyun.com/sr_19930829/article/details/21476287

查找最后一次出现字符串xxx的位置

#include <iostream>

using namespace std;
int main()
{

  string str = "//bear.jpg";
  int pos= str.find_last_of("/");
  cout<<pos<<endl;

}

查找字符串xxx最后一次出现的位置 并截取此位置到字符串末尾

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main()
{

  char fp[500] = "/host/HY/linux/GTK/HTYPaint/bear.jpg";
  string ptr = strrchr(fp, '/');
  cout<<ptr<<endl;

}

查找字符串xxx第一次出现的位置 并截取此位置到字符串末尾

strchr

把字符串以一个字符 一个字符串 多个字符来分割
https://blog.youkuaiyun.com/zhangxiong1985/article/details/84503341

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

//以,来分割字符串 分割后,消失1,2,.3->1 2 .3
std::vector<std::string> shape_vec;
boost::split(shape_vec,op_stru0.inputs_shape,boost::is_any_of(","),boost::token_compress_on);

//以,或.来分割字符串 分割后,.消失1,2,.3->1 2 3
std::vector<std::string> shape_vec;
boost::split(shape_vec,op_stru0.inputs_shape,boost::is_any_of(",."),boost::token_compress_on);

//以abc作为整体来分割efadabcr->efad r
#include <boost/regex.hpp>
    #include <boost/algorithm/string/regex.hpp>

    std::string text = "efadabcr";
    std::vector<std::string> results;    
    boost::split_regex(results, text, boost::regex("abc"));

format
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值