c++ 获取数字字符串字串

点墨 / 163 /

ChatGPT 可用网址,仅供交流学习使用,如对您有所帮助,请收藏并推荐给需要的朋友。
https://ckai.xyz

c++ 获取数字字符串的子串数值,比如给定字符串"123456",要获取第三位和第四位的数值,这里是34。

使用substr

使用substr截取字串,再使用c_str()获取字符数组,再使用atoi()转换为数字

构造字符数组

直接使用索引获取字符,构建字符数组,再使用atoi()转换为数字

代码

#include <string>
#include <iostream>
#include <chrono>
using namespace std;

int main(int argc, char* argv[]) {


    string val = "123";
    int total = 1000000;

    std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
    for (int i = 0; i < total; i++) {
        int tmp = atoi(val.substr(1, 2).c_str());
    }
    std::chrono::time_point<std::chrono::system_clock> end = std::chrono::system_clock::now();
    std::chrono::microseconds diff = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    cout << "using substr:" << diff.count() << "ms" << endl;

    start = std::chrono::system_clock::now();
    for (int i = 0; i < total; i++) {
        char vals[2] = { val[1],val[2] };
        int tmp = atoi(vals);
    }
    end = std::chrono::system_clock::now();
    diff = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    cout << "using char[]:" << diff.count() << "ms" << endl;
    return 0;
}

执行结果

image.png

结论

使用字符直接构造,性能是substr的十倍左右


c++ 获取数字字符串字串
作者
点墨
许可协议
CC BY 4.0
发布于
2023-08-29
修改于
2025-02-06
Bonnie image
尚未登录