C++-এ স্ট্রিংয়ের শুরু ও শেষে থাকা হোয়াইটস্পেস (স্পেস, ট্যাব, নিউলাইন) মুছে ফেলাকে ট্রিমিং (trimming) বলে। STL-এ সরাসরি ট্রিম ফাংশন নেই, কিন্তু Boost লাইব্রেরি বা C++17/20 ফিচার ব্যবহার করে সহজে করা যায়।
পদ্ধতি ১: Boost String Algorithm (সর্বাধিক পপুলার)
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
int main() {
string s = " Hello World ";
cout << "Before: '" << s << "'" << endl;
boost::trim_left(s); // বাম পাশ
cout << "After trim_left: '" << s << "'" << endl;
boost::trim_right(s); // ডান পাশ
cout << "After trim_right: '" << s << "'" << endl;
string s2 = " Trim Both ";
boost::trim(s2); // দুপাশ
cout << "After trim: '" << s2 << "'" << endl;
return 0;
}
আউটপুট
Before: ' Hello World ' After trim_left: 'Hello World ' After trim_right: 'Hello World' After trim: 'Trim Both'
পদ্ধতি ২: C++17/20 Standard Library Only (Boost ছাড়া)
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
// Left trim
static inline void ltrim(string& s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) {
return !isspace(ch);
}));
}
// Right trim
static inline void rtrim(string& s) {
s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !isspace(ch);
}).base(), s.end());
}
// Trim both
static inline void trim(string& s) { ltrim(s); rtrim(s); }
int main() {
string s = " Hello World ";
trim(s);
cout << "'" << s << "'" << endl; // 'Hello World'
}
পদ্ধতি ৩: C++23 std::trim (প্রস্তাবিত)
C++23-এ <string>-এ std::trim, std::ltrim, std::rtrim যোগ হতে পারে (এখনও ফাইনাল নয়)।
সেরা অনুশীলন: প্রজেক্টে Boost আছে থাকলে boost::algorithm::trim ব্যবহার করুন। নেই থাকলে উপরের কাস্টম ফাংশনগুলো কপি করুন। isspace-এ unsigned char キャスト দিন (UB এড়াতে)।