split というのは、文字列を区切り文字で分割する操作を行う関数です。
たとえば "apple,banana,grape" をカンマで分けると ["apple", "banana", "grape"] になる機能です。Python だと str.split(",") という感じで頻繁に使用する機能です。
ところで、 c++ の標準ライブラリには他の言語によくある split がありません。
図書「改訂版3版 C++ ポケットリファレンス」の229ページに記載されている「split の実装」を実際に作成して試してみます。
c++ の標準ライブラリには他の言語によくある split がありません。
図書「改訂版3版 C++ ポケットリファレンス」の229ページに記載されている「split の実装」を実際に作成して試してみます。
| コンパイラ : | gcc, | 9.3.0 |
| OS : | Ubuntu, | 20.04 (Windows11 WSL) |
#include <iostream> // cout, EXIT_SUCCESS
#include <string> // string
#include <vector> // vecotr
#include <regex> // regex, sregex_token_iterator
std::vector<std::string> split(std::string&& s, std::regex&& pattern){
std::sregex_token_iterator first(s.begin(), s.end(), pattern, -1);
std::sregex_token_iterator last;
return std::vector<std::string>(first, last);
}
void print( std::vector<std::string>& s){
for ( const std::string x : s){
std::cout << x << std::endl;
}
}
int main(){
// test pattern 1.
{
std::string s = "123,456,789";
// 文字列をカンマで分割する
std::vector<std::string> result = split(move(s), std::regex(","));
// 出力
print(result);
}
// test pattern 2.
{
std::string s = "1, 23 ,456, 7 ,89";
// 文字列をカンマとスペースで分割する
std::vector<std::string> result = split(move(s), std::regex("[, ]+"));
// 出力
print(result);
}
return EXIT_SUCCESS;
}
123 456 789 1 23 456 7 89
本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。
| 2022-11-18 | - | ページデザイン更新 |
| 2021-11-07 | - | 新規作成 |