Click here to Skip to main content
12,700,567 members (30,607 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++

i need a very simple solution to do this:
for example :
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 26-Dec-12 2:14am
Updated 26-Dec-12 2:19am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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"
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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):

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170118.1 | Last Updated 26 Dec 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100