Skip to main content

Raymii.org Raymii.org Logo

Quis custodiet ipsos custodes?
Home | About | All pages | Cluster Status | 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


❗ This post is over one year old. It may no longer be up to date. Opinions may have changed.

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.

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $100 credit for 60 days.

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