乐趣区

关于c++:c-获取数字字符串字串

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;
}

执行后果

论断

应用字符间接结构,性能是 substr 的十倍左右

退出移动版