C++でのsplit関数の使い方は何ですか?

C++には組み込みのsplit関数はありません。しかし、類似の機能を実現するために他の方法を使用することができます。以下はよく使われる実装方法の一つです:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;
    
    while (getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    
    return tokens;
}

int main() {
    std::string str = "Hello,World,Split,Example";
    char delimiter = ',';
    
    std::vector<std::string> tokens = split(str, delimiter);
    
    for (const auto& token : tokens) {
        std::cout << token << std::endl;
    }
    
    return 0;
}

上記のコードは、分割関数を定義しており、文字列と区切り文字を受け取り、分割されたサブ文字列が含まれるベクタを返します。 main関数では、コンマを区切り文字として使用して文字列を分割し、その結果を表示しています。

結果は:

Hello
World
Split
Example

これは基本的なsplit関数の実装方法です。必要に応じて変更や拡張を行うことができます。

bannerAds