सी में एक स्ट्रिंग से अग्रणी और अनुगामी रिक्त स्थान को हटाना
सी में स्ट्रिंग हेरफेर में अक्सर स्ट्रिंग से अनावश्यक रिक्त स्थान को हटाना शामिल होता है। यह डेटा सफाई या टेक्स्ट प्रोसेसिंग जैसे कार्यों के लिए विशेष रूप से उपयोगी हो सकता है। और तरीकों का पता लगाएं। ये फ़ंक्शन क्रमशः स्ट्रिंग में पहले और अंतिम गैर-व्हाट्सएप वर्ण ढूंढते हैं। इन मानों का उपयोग करके, कोई उस सबस्ट्रिंग को प्राप्त कर सकता है जिसमें गैर-व्हाट्सएप वर्ण शामिल हैं:
std::stringट्रिम(const std::string& str, const std::string&whitespace = "\t") { स्थिरांक ऑटो strBegin = str.find_first_not_of(व्हाइटस्पेस); यदि (strBegin == std::string::npos) वापस करना ""; // कोई सामग्री नहीं स्थिरांक ऑटो strEnd = str.find_last_not_of(व्हाइटस्पेस); स्थिरांक ऑटो strRange = strEnd - strBegin 1; वापसी str.substr(strBegin, strRange); }
शब्दों के बीच अतिरिक्त रिक्त स्थान हटानाstd::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin 1; return str.substr(strBegin, strRange); }
std::string कम(const std::string& str, const std) ::स्ट्रिंग& भरण = " ", स्थिरांक std::string& \टी") { // पहले ट्रिम करें स्वचालित परिणाम = ट्रिम(str, रिक्त स्थान); // उप श्रेणियों को बदलें ऑटो स्टार्टस्पेस = परिणाम.find_first_of(व्हाइटस्पेस); जबकि (beginSpace != std::string::npos) { स्थिरांक ऑटो एंडस्पेस = परिणाम.find_first_not_of(व्हाइटस्पेस, बिगस्पेस); कॉन्स्ट ऑटो रेंज = एंडस्पेस - स्टार्टस्पेस; परिणाम.प्रतिस्थापन(प्रारंभअंतरिक्ष, श्रेणी, भरण); कॉन्स्ट ऑटो न्यूस्टार्ट = बिगस्पेस फिल.लेंथ(); बिगिनस्पेस = परिणाम.find_first_of(व्हाट्सएप, न्यूस्टार्ट); } वापसी परिणाम; }
उदाहरण उपयोगstd::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") { // trim first auto result = trim(str, whitespace); // replace sub ranges auto beginSpace = result.find_first_of(whitespace); while (beginSpace != std::string::npos) { const auto endSpace = result.find_first_not_of(whitespace, beginSpace); const auto range = endSpace - beginSpace; result.replace(beginSpace, range, fill); const auto newStart = beginSpace fill.length(); beginSpace = result.find_first_of(whitespace, newStart); } return result; }
const std::string foo = " बहुत ज्यादा\t \tspace\t\t\t "; const std::string bar = "one\ntwo"; std::cout आउटपुट:
[बहुत अधिक जगह] [बहुत अधिक जगह] [बहुत ज्यादा जगह] [एक दो]
अस्वीकरण: उपलब्ध कराए गए सभी संसाधन आंशिक रूप से इंटरनेट से हैं। यदि आपके कॉपीराइट या अन्य अधिकारों और हितों का कोई उल्लंघन होता है, तो कृपया विस्तृत कारण बताएं और कॉपीराइट या अधिकारों और हितों का प्रमाण प्रदान करें और फिर इसे ईमेल पर भेजें: [email protected] हम इसे आपके लिए यथाशीघ्र संभालेंगे।
Copyright© 2022 湘ICP备2022001581号-3