সিঙ্গল "এলিগ্যান্ট" পদ্ধতি নেই - পঠনীয়তা vs পারফরম্যান্স ট্রেড-অফ। দুটি সাধারণ পদ্ধতি:
১. stringstream (স্পেস-সেপারেটেড ওয়ার্ড)
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp;
stringstream str_strm(str);
vector<string> words;
while(str_strm >> tmp) {
// চেক: empty, punctuation strip
words.push_back(tmp);
}
}
২. getline কাস্টম ডিলিমিটার দিয়ে
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
stringstream str_strm("Hello,from,the,dark,side");
string tmp;
vector<string> words;
char delim = ',';
while(getline(str_strm, tmp, delim)) {
words.push_back(tmp);
}
}
আধুনিক C++ (C++20 Ranges)
#include <string>
#include <ranges>
#include <views>
auto words = "Hello from the dark side"
| std::views::split(' ')
| std::views::transform([](auto&& r) { return std::string_view(&*r.begin(), std::ranges::distance(r)); });
// লেজি, জিরো-অ্যালোকেশন (string_view), কম্পোজেবল
সুপারিশ: সিম্পল কেসে stringstream। পারফরম্যান্স-ক্রিটিক্যালে string_view + ম্যানুয়াল পার্সিং বা C++20 views::split।