C/C++ में स्ट्रिंग के शब्दों पर पुनरावृति करने का कोई एक "सबसे सुंदर" तरीका नहीं है; यह पठनीयता, प्रदर्शन और आवश्यकताओं पर निर्भर करता है। यहां दो सामान्य और प्रभावी दृष्टिकोण दिए गए हैं:
विधि 1: std::stringstream का उपयोग (सरल और पठनीय)
std::stringstream ऑपरेटर >> का उपयोग करके व्हाइटस्पेस द्वारा अलग किए गए शब्दों को निकालता है। यह डिफ़ॉल्ट रूप से कई स्पेस, टैब और नई लाइनों को संभालता है।
उदाहरण
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "Hello from the dark side";
std::stringstream ss(str);
std::string word;
std::vector<std::string> words;
while (ss >> word) {
// यहां word की जांच करें (जैसे खाली नहीं, विराम चिह्न हटाएं)
words.push_back(word);
}
// शब्दों का उपयोग करें
for (const auto& w : words) {
std::cout << w << '\n';
}
return 0;
}
विधि 2: कस्टम डिलीमीटर के साथ std::getline (अधिक नियंत्रण)
यदि आपको विशिष्ट डिलीमीटर (जैसे कॉमा, सेमीकॉलन) की आवश्यकता है, तो std::getline का उपयोग करें।
उदाहरण
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "apple,banana;cherry|date";
std::stringstream ss(str);
std::string token;
std::vector<std::string> tokens;
char delim = ','; // डिलीमीटर बदलें
while (std::getline(ss, token, delim)) {
// टोकन प्रोसेस करें (ट्रिमिंग, आदि)
tokens.push_back(token);
}
return 0;
}
आधुनिक C++ (C++17/20) विकल्प
- std::string_view + मैन्युअल पार्सिंग: आवंटन के बिना उच्च प्रदर्शन।
- Range-v3 / C++20 Ranges:
str | ranges::views::split(' ') | ranges::views::transform(...)अभिव्यंजक और आलसी मूल्यांकन। - Boost.Tokenizer: जटिल पार्सिंग नियमों के लिए मजबूत लाइब्रेरी।
सलाह
सामान्य उपयोग के लिए विधि 1 (stringstream) सबसे अच्छा संतुलन प्रदान करती है। उच्च-प्रदर्शन आवश्यकताओं के लिए मैन्युअल पार्सिंग या C++20 रेंज पर विचार करें।