When we take an input from an user, strings can have unwanted whitespaces in the start or end of the string. We can trim the strings to get rid of the extra whitespaces in the start and in the end, but not in the middle of the String.
For example, if a user inputs some whitespace in the starting or ending of his email id, then it should be sent without any leading or trailing whitespaces to the servers for the accurate information.
C++ does not have direct support for string trimming, but we can make use of boost library, a combination of library functions and custom functions to trim the string in C++.
In this article, we will see different ways to trim String in C++.
Table of Contents
Using Boost string algorithms to trim string in C++
We can utilize the trim_right
and trim_left
functions defined in the boost string algorithms. These functions can be used to remove the right and left whitespaces from the string. We can also use the trim_right_copy
or trim_left_copy
functions that will return the trimmed copy of the string.
This library also provides the function trim_copy_if
that will only trim the string if the given condition is satisfied.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> #include <boost> #include <boost> //contains 'is_any_of()' using namespace std; int main() { string str1, str2, str3; getline(cin, str1); getline(cin, str2); getline(cin, str3); cout << "Original Input String1: " << str1 << endl; //Remove whitespaces from both sides boost::trim(str1); //Changes are directly made to original string cout << "String after trim(): "<<str1 endl and trim_right cout input string2: str2 boost::trim_left whitespaces from left side after trim_left boost::trim_right right functions is returned changes are not made to original string output_string="boost::trim_left_copy(str3);" string: str3 trim: output_string2="boost::trim_right_copy(str3);" leading the mobile number trim_left_if it can be done for will check if there zeros m_num="000987654321" boost::trim_left_if without zeros: return></str1></boost></boost></string></iostream> |
Input
“ C++ Programming “
“ Java Programming “
Output
String after trim(): Java2 Blog
Original Input String2: C++ Programming
String after trim_left(): C++ Programming
String after trim_right(): C++ Programming
Original string: Java Programming
Output String after left trim: Java Programming
Output String after right trim: Java Programming
Mobile Number without leading zeros: 987654321
Using find_first_not_of() and
find_last_not_of()` to trim strings in C++
In this method, we will use find_first_not_of()
and find_last_not_of()
to create left trim and right trim functions. These two functions can be used to search the string for the first and last character that does not match with the characters specified in the argument of the functions.
If position is also specified in the function, then it will only include the characters present at that position or after that position (ignores all the characters present before the position).
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> #include <string> using namespace std; //Function to trim string from both right and left sides. string trim_complete(string str) { const char* whitespace_type = " "; str.erase(str.find_last_not_of(whitespace_type) + 1); str.erase(0,str.find_first_not_of(whitespace_type)); return str; } //Function to trim string from left side only string trim_left(string str){ const char* whitespace_type=" "; str.erase(0,str.find_first_not_of(whitespace_type)); return str; } //Function to trim string from right side only string trim_right(string str){ const char* whitespace_type=" "; str.erase(str.find_last_not_of(whitespace_type) + 1); return str; } int main() { string str1, str2; getline(cin, str1);//Input for first string cout<<"Original String 1: " <<str1 str1="trim_complete(str1);" cout trim: for second string getline str2 left right return></str1></string></iostream> |
Input
“ C++ Programming “
Output
After Trim: Java2Blog
Original String 2: C++ Programming
After Left Trim: C++ Programming
After Right Trim: C++ Programming
Using find_if()
to trim the string in C++
We can utilize the find_if()
function for making customized functions for left trim and right trim of unwanted characters.
Syntax of find_if():
1 2 3 4 5 |
template <class inp_iteratopr class predicate> Inp_iterator find_if (Inp_iterator start, Inp_iterator end, Predicate, pred) </class> |
Parameters:
start, end
: These are input iterators to the starting and ending positions in the sequence. The range [start, end) contains all the elements between start and end. It does not include the element pointed by end and includes the element pointed by start.
pred
: It is a unary function that can accept an element in the range as arguments and it returns a bool value.
Return Value
: It returns an iterator to the first element for which pred returns true. If pred is not true for any element, then it will return an iterator to the last element.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <string> #include <algorithm> using namespace std; //Function to remove whitespaces from the left side string& left_trim(string &str) { auto iter = find_if(str.begin(), str.end(), [](char ch) { return !isspace<char>(ch, locale::classic()); }); str.erase(str.begin(), iter); return str; } //Function to remove whitespaces from the right side string& right_trim(string &str) { auto iter = find_if(str.rbegin(), str.rend(), [](char ch) { return !isspace<char>(ch, locale::classic()); }); str.erase(iter.base(), str.end()); return str; } string& trim(string &str) { return left_trim(right_trim(str)); } int main() { string str1 = " Java2Blog "; string str2 = "\n C++ Programming "; cout <<trim cout right_trim return></trim></char></char></algorithm></string></iostream> |
Output
C++ Programming
C++ Programming
Using stringstream
to trim the strings in C++
We can use the stringstream
method if there are no internal whitespaces. It is a less efficient method because the string gets copied in the stream. If there are any internal whitespaces then it will return the characters before that whitespace.
Note: It is not possible to make left trim and right trim functions in this method. We can directly trim the string from both sides.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <sstream> #include <iostream> #include <string> using namespace std; int main(){ string str = " JAVA2BLOG "; string str2 = " C++ PROGRAMMING "; std::stringstream trim_string; trim_string << str; str.clear(); trim_string >> str; cout<<"String After Trim: " <<str endl str.clear it will not read after first internal whitespace trim_string str2>> str2; cout<<"String After Trim: "<< str2 << endl; return 0; } </str></string></iostream></sstream> |
Output
String After Trim: C++
Using a customized function to trim the strings in C++
Here, we count the number of leading or trailing whitespaces. We get the position where the valid character starts and where it ends, then we return only that part of the string.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <string> #include <iostream> using namespace std; string trim(string str){ int start=0, end= str.size()-1; //assuming no whitespaces present //Remove whitespaces from left //Getting position of the valid character from left for(int i=0; i<str.size i if start="i;" break whitespaces from right position of the valid character for>=0; i--){ if(str[i] != ' '){ end=i; break; } } string final_string=""; for(int i= start; i<=end; i++){ final_string += str[i]; } return final_string; } //Main function int main(){ string str = " JAVA2 BLOG "; cout <<"String After Trim:" << trim(str) <<endl return></endl></str.size></iostream></string> |
Output
Conclusion
We discussed efficient methods to trim strings in C++, though there is no direct support for that. Any method can be used and every method has a different level of complexity. Trimming string can be easy if the above methods are followed.
That’s all about how to trim String in C++.
Happy Learning!!