OneBite.Dev - Coding blog in a bite size

Trim A String In C++

Code snippet for how to Trim A String In C++ with sample and detail explanation

Trimming a string in C++ can be useful in instances where you want to remove leading or trailing spaces. This simple guide will assist you in achieving this task using a clear, step-by-step approach.

Code snippet for Trimming a String in C++

Here’s a simple and effective piece of code you can use to trim a string in C++. This code snippet will trim any leading and trailing spaces from your string.

#include <algorithm> 
#include <cctype>
#include <locale>

// Trim from start (in place)
static inline void ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
        return !std::isspace(ch);
    }));
}

// Trim from end (in place)
static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

// Trim from both ends (in place)
static inline void trim(std::string &s) {
    ltrim(s);
    rtrim(s);
}

Code Explanation for Trimming a String in C++

Let’s break down every piece of the code to understand better how it works.

  1. The <algorithm>, <cctype> and <locale> libraries are included at the beginning. They provide functions that are used within our trimming functions.

  2. The ltrim function is designed to trim leading spaces from the string. It works by erasing characters from the beginning of the string (s.begin()) to the first character (std::find_if) that does not meet the condition std::isspace(). std::isspace() checks if a character is a space.

  3. The rtrim function serves to trim trailing spaces from the string in essentially the same way as ltrim. However, it starts from the end of the string (s.rbegin()) and moves to the last character that does not meet the std::isspace() condition.

  4. The trim function combines both the ltrim and rtrim functions thereby erasing spaces at the beginning and end of the string (s).

Just by calling the trim function on any string, you can easily remove any unwanted spaces. If you only want to remove spaces from the beginning or the end, then ltrim or rtrim can be used respectively.

c-plus-plus