Thinking in C++

My C++ code snips.

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  ");
	std::cout<<"|";
	std::cout<<mystr;
	std::cout<<"|";
}

Output :

|hello|

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: