clear spaces in a string

M

Marc Durufle

I have a string like that " Vertices "
and i want to obtain "Vertices"
I would want to know if there is a simple way to put off spaces on a
string, thank you
 
S

Samuele Armondi

Marc Durufle said:
I have a string like that " Vertices "
and i want to obtain "Vertices"
I would want to know if there is a simple way to put off spaces on a
string, thank you

--
Marc Durufle
Inria Rocquencourt
Tel : 01 39 63 56 27
--------------------------

Try this:
std::string s = " Vertices ";
std::string::iterator it = std::remove_if(s.begin(), s.end(),
std::bind2nd(std::equal_to<char>(), ' '));
s = std::string(s.begin(), it);
HTH,
S. Armondi
 
M

Mike Wahler

Marc Durufle said:
I have a string like that " Vertices "
and i want to obtain "Vertices"
I would want to know if there is a simple way to put off spaces on a
string, thank you

--
Marc Durufle
Inria Rocquencourt
Tel : 01 39 63 56 27
--------------------------

#include <iostream>
#include <sstream>
#include <string>

std::string strip(const std::string& s)
{
std::string result;
std::istringstream(s) >> result;
return result;
}

int main()
{
std::cout << '*'
<< strip(" Vertices ")
<< '*'
<< '\n';

return 0;
}

-Mike
 
R

Russell Hanneken

Mike said:
std::istringstream(s) >> result;

Mike,

I don't think that will compile; you're passing a temporary by non-const
reference. I believe you have to do something like this:

std::istringstream iss(s);
iss >> result;

Regards,

Russell Hanneken
(e-mail address removed)
 
I

Ivan Vecerina

Marc Durufle said:
I have a string like that " Vertices "
and i want to obtain "Vertices"
I would want to know if there is a simple way to put off spaces on a
string, thank you

Note: you should specify whether you intend to remove *all* spaces,
or just trim the ones at the beginning and the end of the string.
(several replies so far assume the former).

Here's a way to remove spaces at both ends of the string:
std::string trimmed( std::string const& str, char const* sepSet )
{
std::string::size_type const first = str.find_first_not_of(sepSet);
return ( first==std::string::npos )
? std::string()
: str.substr(first, str.find_last_not_of(sepSet)-first+1);
}

NB: - str is the original string
- sepSet is the list of space characters.
Use for example: " " or " \t" or " \t\n\r" etc.


hth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top