Skip to content

std::string 的工具函数 - 用 isspace 实现 trim 函数 #10

@jamesfancy

Description

@jamesfancy

CodeProject 上有朋友说我不应该将空白字符限制在 " /t/n/r" 以内,应该使用 isspace 来实现 trim 函数以处理 Unicode 的空白字符。此话在理,所以将 trim 的三个函数改了一下。(参阅上一篇《std::string的工具函数》

string trimLeft(const string& str) {
    string t = str;
    for (string::iterator i = t.begin(); i != t.end(); i++) {
        if (!isspace(*i)) {
            t.erase(t.begin(), i);
            break;
        }
    }
    return t;
}

string trimRight(const string& str) {
    if (str.begin() == str.end()) {
        return str;
    }

    string t = str;
    for (string::iterator i = t.end() - 1; i != t.begin(); i--) {
        if (!isspace(*i)) {
            t.erase(i + 1, t.end());
            break;
        }
    }
    return t;
}

string trim(const string& str) {
    string t = str;

    string::iterator i;
    for (i = t.begin(); i != t.end(); i++) {
        if (!isspace(*i)) {
            t.erase(t.begin(), i);
            break;
        }
    }

    if (i == t.end()) {
        return t;
    }

    for (i = t.end() - 1; i != t.begin(); i--) {
        if (!isspace(*i)) {
            t.erase(i + 1, t.end());
            break;
        }
    }

    return t;
}

原理很浅显,就是把原来用 find_first_offind_first_not_of 实现的查找换成循环,自己用 isspace 来判断。本来想参考一下 boost 的实现,不过发现它的代码实在有点复杂,所以还是自己用简单的循环来解决了。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions