Skip to content
Related Articles

Related Articles

boost::trim in C++ library

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 14 Jul, 2021
Improve Article
Save Article

This function is included in the “boost/algorithm/string” library. The Boost String Algorithms Library provides a generic implementation of string-related algorithms which are missing in STL. The trim function is used to remove all leading or trailing white spaces from the string. The input sequence is modified in place.

  • trim_left(): Removes all leading white spaces from the string.
  • trim_right(): Removes all trailing white spaces from the string.
  • trim(): Removes all leading and trailing white spaces from the string.

Syntax:

Template:
trim(Input, Loc);

Parameters:
Input: An input sequence
Loc: A locale used for ‘space’ classification

Returns: The modified input sequence without leading or trailing white spaces.

Examples:

Input: ”    geeks_for_geeks    ” 
Output: Applied left trim: “geeks_for_geeks    ” 
Applied right trim: ”    geeks_for_geeks” 
Applied trim: “geeks_for_geeks” 
Explanation: 
The trim_left() function removes all the leading white spaces.
The trim_right() function removes all the trailing white spaces.
The trim() function removes all the leading and trailing white spaces.

Below is the implementation to remove white spaces from string using the function boost::trim():

C++




// C++ program to remove white spaces
// from string using the function
// boost::trim function
#include <boost/algorithm/string.hpp>
#include <iostream>
using namespace boost::algorithm;
using namespace std;
  
// Driver Code
int main()
{
    // Given Input
    string s1 = "    geeks_for_geeks    ";
    string s2 = "    geeks_for_geeks    ";
    string s3 = "    geeks_for_geeks    ";
  
    // Apply Left Trim on string, s1
    cout << "The original string is: \""
         << s1 << "\" \n";
    trim_left(s1);
    cout << "Applied left trim: \""
         << s1 << "\" \n\n";
  
    // Apply Right Trim on string, s2
    cout << "The original string is: \""
         << s2 << "\" \n";
    trim_right(s2);
    cout << "Applied right trim: \""
         << s2 << "\" \n\n";
  
    // Apply Trim on string, s3
    cout << "The original string is: \""
         << s3 << "\" \n";
    trim(s3);
    cout << "Applied trim: \"" << s3
         << "\" \n";
  
    return 0;
}


Output:

The original string is: "    geeks_for_geeks    " 
Applied left trim: "geeks_for_geeks    " 

The original string is: "    geeks_for_geeks    " 
Applied right trim: "    geeks_for_geeks" 

The original string is: "    geeks_for_geeks    " 
Applied trim: "geeks_for_geeks"

Time Complexity: O(N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!