从字符串中删除字符的第一个和最后一个实例

Remove first and last instance of a char from a string

本文关键字:第一个 最后一个 实例 字符 字符串 删除      更新时间:2023-10-16

我有一个.ini文件,我在其中声明了如下部分:

[章节名称]

我想摆脱"["和"]"以仅在部分名称中读取,目前我正在使用它来实现我想要的:

line.substr(1, line.size() - 2);

但这只会删除第一个和最后一个角色,无论它们是什么。我正在寻找一种优雅的方式来删除第一次出现的"["和最后一次出现的"]"。提前感谢!

编辑:我尝试使用这个:

void TrimRight(std::string str, std::string chars)
{
    str.erase(str.find_last_not_of(chars) + 1);
}
void TrimLeft(std::string str, std::string chars)
{
    str.erase(0, str.find_first_not_of(chars));
}
TrimLeft(line, "[");
TrimRight(line, "]");

但这并不是出于某种奇怪的原因删除它们......

你可以使用字符串 front() 和 back() 成员函数:

#include <iostream>
#include <string>
int main() {
    std::string s = "[Section]";
    if (s.front() == '[' && s.back() == ']') {
        s.erase(0, 1);
        s.pop_back();
    }
    std::cout << s;
}

或者,如果您希望删除其中之一:

if (s.front() == '[') {
    s.erase(0, 1);
}
if (s.back() == ']') {
    s.pop_back();
}

.pop_back()函数删除最后一个字符。您的函数按值而不是引用接受参数。以下是函数变体:

一个void函数,您可以在其中通过引用传递参数:

void trimstr(std::string& s) {
    if (s.front() == '[' && s.back() == ']') {
        s.erase(0, 1);
        s.pop_back();
    }
}

和返回std::string的函数:

std::string gettrimmed(const std::string& s) {
    std::string temp = s;
    if (temp.front() == '[' && temp.back() == ']') {
        temp.erase(0, 1);
        temp.pop_back();
    }
    return temp;
}

使用string::find_first_of()string::find_last_of()查找两个字符的位置。然后获取这两个位置之间的子字符串:

int main() {
    std::string s("[SectionName]");
    size_t first = s.find_first_of('[');
    size_t last = s.find_last_of(']');
    if (std::string::npos != first && std::string::npos != last)
    {
        std::cout << s.substr(first + 1, last - first - 1);
    }
    return 0;
}

演示

相关文章: