Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hello

i need a very simple solution to do this:
for example :
C++
string str="  Alex       ";
 string result="Alex";

i tried some ways with erase and replace,but they weren't suitable for my case.

actually;i want sort a vector of Objects by Their NAME(first char).

thanks !
Posted
Updated 26-Dec-12 1:19am
v4

Assuming you are using managed code, there is the Trim method[^] If what you are trying to do is remove the leading and trailing spaces, then that will do it, and would explain why replace "wasn't suitable"
 
Share this answer
 
If you want to trim spaces at both ends with std::string class object, you can use std::string::find_first_not_of[^] and std::string::string/find_last_not_of[^.

A bit of logic and std::string::substr[^], you are able to create a function that will do the same as .NET System::String::Trim[^] function does for managed strings.

The code should look like this (not tested):

C++
using namespace std;

string trim(const string &source, const string &trim_chars)
{
  size_t pos1 = source.find_first_not_of(trim_chars);
  size_t pos2 = source.find_last_not_of(trim_chars);

  // Optional: optimize case where the string is already trimmed.
  if (pos1 == string::npos && pos2 == string::npos) { return source; }

  if (pos1 == string::npos) { pos1 = 0; }
  if (pos2 == string::npos) { pos2 = source.length(); }

  size_t trimmed_length = pos2 - pos1;
  return source.substr(pos1, trimmed_length);
}

string trim(const string &source)
{
  string trim_chars(" \t\r\n");  // Whatever you want to uses by default.
  return trim(source, trim_chars);
}


If you want to remove all spaces, then you might uses similar functions in a loop and construct a new string on the fly. Essentially, you would find first char that is not a space and next space after that and copy that part and then repeat until the remainding part of the string does not contains spaces anymore.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900