Thinking in C++

My C++ code snips.

Posts Tagged ‘Java trim() in C++’

C++ Trim

Posted by Abhi on February 8, 2012

C++ standard library lacks a trim() function similar to what Java provides. Here is a simple function in C++ which can achieve similar results.

#include <string>

std::string trim(const std::string& str)
	using std::string;
	string::size_type pos = str.find_first_not_of(" ");
	string::size_type pos1 = str.find_last_not_of(" ");
	string trimmed = str.substr(pos,pos1-pos+1);
	return trimmed;

Usage :

#include <iostream>
#include <string>
int main()
	std::string mystr = trim(" hello  ");

Output :


Pardon me for the lack of tabs, apparently WordPress does not allow you to add tabs to your posts.

Edit: My bad. WordPress does provide support to paste code. Read more here


Posted in C++ | Tagged: , , | Leave a Comment »