trim(): This function is included in the "boost/algorithm/string" library. This library contains some brilliant methods which help in accomplishing string manipulations that are lacking in STL library.
This function "trim" is used to remove all the leading and trailing white-spaces in the string i.e., all the spaces present on the start and the end of the string as shown in the below examples:
Examples:
1. Original String: " Hello nice to meet you "
Modified String: "Hello nice to meet you"
2. Original String: "You are using boost "
Modified String: "You are using boost"
header file:
boost/algorithm/string.hpp
syntax:
trim(input , loc);
parameters:
input : an input sequence
loc : a locale used for space classification
The modification of the string is done in-place if trim() is used.
There is another variation present i.e., trim_copy() , which takes the same parameters as input, but instead of modifying the string in-place it returns a copy of the modified string while keeping the original string as it is.
SAMPLE CODE:
#include<boost/algorithm/string.hpp>
#include<iostream>
using namespace std;
using namespace boost::algorithm;
int main()
{
string s1 = " Welcome to Boost ";
string s2 = s1;
string s3 = " You are using boost library ";
trim(s2);
string newString = trim_copy(s3);
cout<<"EXAMPLE 1"<<endl;
cout<<"The original string: ";
cout<<s1<<"##part not in string##"<<endl;
cout<<"The modified string: ";
cout<<s2<<"##part not in string##"<<endl;
cout<<"EXAMPLE 2"<<endl;
cout<<"The original string: ";
cout<<s3<<"##part not in string##"<<endl;
cout<<"The modified string: ";
cout<<newString<<"##part not in string##"<<endl;
}
OUTPUT:
EXPLANATION:
As we an observe from the above code that trim() takes any string as input and it removes all the leading and trailing whitespaces. It leaves the rest of characters and symbols untouched.
Similarly, trim_copy() instead of modifying the original string i.e., "s3", it returns the modified string to "newString".
Comments