SupaDupa
SupaDupa

Reputation: 181

Remove first and last instance of a char from a string

I have a .ini file and in it i declare Sections like:

[SectionName]

I want to get rid of '[' and ']' to just read in the SectionName, currently i'm using this to achieve what i want:

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

But this gets only rid of the first and last Character, no matter what they are. I'm looking for an elegant way to delete the first occurrence of '[' and last occurrence of ']'. Thanks in advance!

EDIT: I tried using this:

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, "]");

But this is not removing them, for some weird reason...

Upvotes: 1

Views: 3676

Answers (2)

Ron
Ron

Reputation: 15501

You can utilize the strings front() and back() member functions:

#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;
}

or if you want either removed:

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

The .pop_back() function removes the last character. Your functions are accepting arguments by value, not reference. Here are the function variations:

A void function where you pass the parameter by reference:

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

and the function that returns a 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;
}

Upvotes: 3

CinCout
CinCout

Reputation: 9619

Use string::find_first_of() and string::find_last_of() to find the positions of the two characters. Then get the substring between those two positions:

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;
}

Demo

Upvotes: 2

Related Questions