向阳花木(四)C++string工具

1. string关键字

1.1 API

常量定义
std::string::size_type
std::string::npos
API定义含义
c_str()函数返回的是一个指向正规C字符串的指针,内容与本string串相同
length()
substr()substr(size_type pos = 0, size_type count = npos)
pos:所需的子字符串的起始位置
count: 复制的字符数目
返回值:一个定的位置开始的子字符串
复制子字符串
find()std::string str = "I'm from China.";
std::string sep= "China";
std::string::size_type pos = str.find(sep);

1.2 取字符
取首尾字符的方法

2. 数据转换

2.1 string与QString、int、double、long之间的转换

  1. string与QString互为转换
//string与QString互为转换
QString qstr = "12";
std::string s = qstr.toStdString();     //QString转string
QString qs = QString::fromStdString(s); //string转QString
  1. string与int、double、long互为转换
  • string转化int、double、long
//string转化int、double、long
int data_int = std::atoi(input.c_str());       //string 转化为 int
double data_double = std::atof(input.c_str()); //string 转化为 double
long data_long = std::atol(input.c_str());     //string 转化为 long
  • int、double、long转化string
//int、double、long转化string
int input_int = 10;
std::string str = std::to_string(input_int);

2.2 string与double转换精度处理

3. 字符串工具接口

3.1 字符串分割工具

/**
  * @brief 字符串分割函数
  * @param str 要分割的字符串
  * @param sep Separator,分隔符
  *
  * @return 分割后的字符串列表
  */
std::vector<std::string> StrTool::SplitString(const std::string& str,
                                              const std::string& sep) {
    std::vector<std::string> res;
    //pos1起时位置,pos2下一个sep的起时位置
    std::string::size_type pos1 = 0, pos2 = str.find(sep);
    while(std::string::npos != pos2) {
        res.push_back(str.substr(pos1, pos2 - pos1));
        pos1 = pos2 + sep.size();
        pos2 = str.find(sep, pos1);
    }
    if(pos1 != str.length()) {
        res.push_back(str.substr(pos1));
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小老鼠不吃猫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值