C++对string字符串进行trim和split操作

c++小白的学习笔记;
记录c++ trim和split的实现方法:

#include 
#include 
#include 
#include 

using namespace std;

namespace
{
    bool isntspace(const char &ch)
    {
        return !isspace(ch);
    }
} // end of namespace

const std::string ltrim(const std::string &s)
{
    std::string::const_iterator iter = find_if(s.begin(), s.end(), isntspace);
    return std::string(iter, s.end());
}

const std::string rtrim(const string &s)
{
    std::string::const_iterator iter = find_if(s.rbegin(), s.rend(), isntspace).base();
    return std::string(s.begin(), iter);
}

const std::string trim(const std::string &s)
{
    std::string::const_iterator iter1 = find_if(s.begin(), s.end(), isntspace);
    std::string::const_iterator iter2 = find_if(s.rbegin(), s.rend(), isntspace).base();

    return iter1 < iter2 ? string(iter1, iter2) : std::string("");
}

const void Stringsplit(const string& str, const string& split, vector<string>& res)
{
	std::regex reg(split);		// 匹配split字符串
	std::sregex_token_iterator pos(str.begin(), str.end(), reg, -1);
	decltype(pos) end;              // 自动推导类型 
	for (; pos != end; ++pos)
	{
		res.push_back(pos->str());
	}
}

int main()
{
    cout << "hello world!\n";

    // 待解析数据
    std::string temp = "           Java Heap:     3324                          29460   ";
    cout << "temp:" << temp << "\n";

    // trim移除前后空格;
    std::string trimTemp = trim(temp);
    cout << "trimTemp:" << trimTemp << "\n";

    // 获取后面的3324   29460数据
    vector<std::string> list;
    Stringsplit(trimTemp, ":", list);
    std::string value = list[1]; //值是"     3324                          29460"

    //再做一次trim,移除3324前面的空格
    std::string trimValue = trim(value);

    // 用空格分割,获取3324数据和29460数据;
    vector<std::string> valueList;
    Stringsplit(trimValue, " ", valueList);
    for (size_t i = 0; i < valueList.size(); i++)
    {
        cout << "splitItem:" << i << "value:" <<  valueList[i] << "\n";
    }

    return 0;
}

你可能感兴趣的:(c++,c++,java,开发语言)