본문 바로가기
자질구레

[C++] split함수

by jonnwon 2024. 10. 1.
728x90
반응형

delim이 string

#include <bits/stdc++.h>
using namespace std;

vector<string> split(const string& input, const string& delim) {
    vector<string> res;
    auto start = 0;
    auto end = input.find(delim);
    while (end != string::npos) {
        res.push_back(input.substr(start, end - start));
        start = end + delim.size();
        end = input.find(delim, start);
    }
    res.push_back(input.substr(start));
    return res;
}

 

 

delim이 char

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

string s;
int main() {
    getline(cin, s);
    stringstream ss(s);

    string buffer;
    while (getline(ss, buffer, ' ')) {
        cout << buffer << endl;
    }
    cout << endl;
    return 0;
}

 

 

delim 이 공백이고 앞에 공백 있을 때

#include <bits/stdc++.h>
using namespace std;

string s;
int res = 0;
int main() {
    getline(cin, s);
    stringstream ss(s);

    string buffer;
    while (ss >> buffer) {
        res++;
    }
    cout << res;
    return 0;
}

 

728x90