Skip to main content

Raymii.org Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

C++ Remove leading or trailing characters from std::string

Published: 18-07-2020 | Author: Remy van Elst | Text only version of this article


Table of Contents


Here's a small snippet to remove leading or trailing characters from a std::string in C++. I use it to strip leading and trailing zeroes in a game score display function.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

Code

These are the two functions, one to remove leading zeroes and one to remove trailing zeroes:

static void removeTrailingCharacters(std::string &str, const char charToRemove) {
    str.erase (str.find_last_not_of(charToRemove) + 1, std::string::npos );
}

static void removeLeadingCharacters(std::string &str, const char charToRemove) {
    str.erase(0, std::min(str.find_first_not_of(charToRemove), str.size() - 1));
}

Usage example

Example program and output:

#include <iostream>
#include <string>

static void removeTrailingCharacters(std::string &str, const char charToRemove) {
    str.erase (str.find_last_not_of(charToRemove) + 1, std::string::npos );
}

static void removeLeadingCharacters(std::string &str, const char charToRemove) {
    str.erase(0, std::min(str.find_first_not_of(charToRemove), str.size() - 1));
}

int main() {
    std::string example1 = "0000abc000";
    std::cout << "before trailing removal: " << example1 << std::endl;
    removeTrailingCharacters(example1, '0');
    std::cout << "after trailing removal:  " << example1 << std::endl;
    std::cout << std::endl;
    std::cout << "before leading removal:  " << example1 << std::endl;
    removeLeadingCharacters(example1, '0');
    std::cout << "after leading removal:   " << example1 << std::endl;

    return 0;
}

Output:

before trailing removal: 0000abc000
after trailing removal:  0000abc

before leading removal:  0000abc
after leading removal:   abc
Tags: c++ , cpp , development , snippets , string