c++ 獲取數字字符串的子串數值性能示例分析
更新時間:2023年11月02日 11:49:44 作者:點墨
這篇文章主要為大家介紹了c++ 獲取數字字符串的子串數值示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
題引
c++ 獲取數字字符串的子串數值,比如給定字符串"123456",要獲取第三位和第四位的數值,這里是34。
方法
1.使用substr
使用substr截取字串,再使用c_str()獲取字符數組,再使用atoi()轉換為數字
2.構造字符數組
直接使用索引獲取字符,構建字符數組,再使用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; }
執(zhí)行結果
結論
使用字符直接構造,性能是substr的十倍左右
以上就是c++ 獲取數字字符串的子串數值性能示例分析的詳細內容,更多關于c++ 數字字符串子串獲取的資料請關注腳本之家其它相關文章!
相關文章
C語言詳細分析講解內存管理malloc realloc free calloc函數的使用
C語言內存管理相關的函數主要有realloc、calloc、malloc、free等,下面這篇文章主要給大家介紹了關于C語言內存管理realloc、calloc、malloc、free函數的相關資料,需要的朋友可以參考下2022-05-05vscode 配置 C/C++編譯環(huán)境(完整教程)
這篇文章主要介紹了vscode 配置 C/C++編譯環(huán)境(完整教程),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09