取出string类型[x,y]区间的两端数组——编程小总结(一)

一、 需求

原料: string test = "[1,100]";
目标: 取出 1、100两个数字;

二、生成结果

在这里插入图片描述

三、代码

可以使用字符串的substr函数来实现取出子串的操作。substr函数的原型为:

string substr (size_t pos, size_t len) const;

其中,pos表示子串的起始位置,len表示子串的长度。

下面是一个示例代码,实现从字符串中取出[x,y]中的xy

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "[1,100]";
    size_t pos1 = str.find("[");
    size_t pos2 = str.find(",");
    size_t pos3 = str.find("]");
    if (pos1 != string::npos && pos2 != string::npos && pos3 != string::npos) {
        string x = str.substr(pos1 + 1, pos2 - pos1 - 1);
        string y = str.substr(pos2 + 1, pos3 - pos2 - 1);
        cout << "x = " << x << ", y = " << y << endl;
    }
    return 0;
}

在上述代码中,使用了字符串的find函数来查找字符串中的左括号、逗号和右括号的位置,如果都存在,则使用substr函数来取出[x,y]中的xy。需要注意的是,substr函数的第一个参数是起始位置,因此需要加上左括号的长度1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

愿天堂没有C++

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

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

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

打赏作者

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

抵扣说明:

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

余额充值