C++ substr() 使用方式

本篇介紹 substr 取出子字串的方式,以及補充一般陣列如何取出子字串

substr用法

substr(參數a, 參數b)

參數a 為要取出子字串的起始索引位置,若要取出 “3” 就輸入該索引位置為 2
參數b 從起始索引往後取幾個字串,若只取 “3” 則輸入 1,取 “34” 則輸入 2。

1
2
3
string s = "123456789";
cout << s.substr(2, 1) << endl; // output: 3
cout << s.substr(2, 2) << endl; // output: 34

補充:陣列方式

s[i][2] : [i] 陣列裡的字串,[2] 指定索引值

1
2
3
4
5
6
vector<string> s = {"123456789"};

for(size_t i = 0; i < s.size(); i++){
cout << s[i][2] << endl; // output: 3
cout << s[i][2] << s[i][3] << endl; // output: 34
}

C++ substr() 使用方式
http://example.com/2024/08/02/Cpp_Library/substr/
Author
Jay
Posted on
August 2, 2024
Updated on
August 2, 2024
Licensed under