Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธี Trim std::string ใน C++ ที่ดีที่สุด

Trim whitespace (space, tab, newline) ด้านซ้าย/ขวา/ทั้งสองข้างของ std::string

ใช้ Boost.StringAlgo (แนะนำ)

#include <boost/algorithm/string.hpp>
using namespace std;

string s = "  Hello World  ";
boost::trim_left(s);  // "Hello World  "
boost::trim_right(s); // "  Hello World"
boost::trim(s);       // "Hello World" (ทั้งสองข้าง)

ไม่ใช้ Boost (C++17+)

// Trim left
auto start = s.find_first_not_of(" \t\n\r");
if (start != string::npos) s = s.substr(start);

// Trim right
auto end = s.find_last_not_of(" \t\n\r");
if (end != string::npos) s = s.substr(0, end + 1);
else s.clear();

C++23: std::trim (Proposed)

ยังไม่มาตรฐาน แต่มี proposal และ library implementations

ผลลัพธ์ตัวอย่าง

Original: (  Hello World  )
After trim_right: (  Hello World)
After trim_left: (Hello World)
After trim: (Hello World)

Boost เร็ว ทดสอบดี รองรับ locale และ predicate customization