c++ 獲取數(shù)字字符串的子串?dāng)?shù)值性能示例分析
題引
c++ 獲取數(shù)字字符串的子串?dāng)?shù)值,比如給定字符串"123456",要獲取第三位和第四位的數(shù)值,這里是34。
方法
1.使用substr
使用substr截取字串,再使用c_str()獲取字符數(shù)組,再使用atoi()轉(zhuǎn)換為數(shù)字
2.構(gòu)造字符數(shù)組
直接使用索引獲取字符,構(gòu)建字符數(shù)組,再使用atoi()轉(zhuǎn)換為數(shù)字
代碼
#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í)行結(jié)果

結(jié)論
使用字符直接構(gòu)造,性能是substr的十倍左右
以上就是c++ 獲取數(shù)字字符串的子串?dāng)?shù)值性能示例分析的詳細內(nèi)容,更多關(guān)于c++ 數(shù)字字符串子串獲取的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C語言詳細分析講解內(nèi)存管理malloc realloc free calloc函數(shù)的使用
C語言內(nèi)存管理相關(guān)的函數(shù)主要有realloc、calloc、malloc、free等,下面這篇文章主要給大家介紹了關(guān)于C語言內(nèi)存管理realloc、calloc、malloc、free函數(shù)的相關(guān)資料,需要的朋友可以參考下2022-05-05
vscode 配置 C/C++編譯環(huán)境(完整教程)
這篇文章主要介紹了vscode 配置 C/C++編譯環(huán)境(完整教程),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

