使用find_first_of()和find_last_of()成员函数可以很方便地实现
一些小的功能,比如从字符串的头尾两端删除空白字符
不触动原字符串,而是返回一个新字符串
//: C03:Trim.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// General tool to strip spaces from both ends.
#ifndef TRIM_H
#define TRIM_H
#include <string>
#include <cstddef>
inline std::string trim(const std::string& s) {
if(s.length() == 0)
return s;
std::size_t beg = s.find_first_not_of(" \a\b\f\n\r\t\v");
std::size_t end = s.find_last_not_of(" \a\b\f\n\r\t\v");
if(beg == std::string::npos) // No non-spaces
return "";
return std::string(s, beg, end - beg + 1);
}
#endif // TRIM_H //