Thread: removing spaces from a string

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    16

    removing spaces from a string

    hey everyone i have a fairly straightforward problem that i cant seem to find an easy answer to. I want to remove the spaces from the beginning of a string. I was wondering if there is a build in function for this that i could take advantage of. I know its not hard, i just dont want to reinvent the wheel. I have the librarys included so i may as well make use of them.

    Code:
     string = "        hello";
    i just want the output to be hello without the leading spaces.



    thanks in advance,
    Brad.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >I want to remove the spaces from the beginning of a string.
    I don't know if this is the easiest way, but try this.
    Code:
       string = string.substr(string.find_first_not_of(' '));

  3. #3
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Well, you could try using remove_if, but writing the predicate for it will be just as much work as just removing the spaces manually (maybe more).

    EDIT 2: Swoopy's Idea can be simplified even more

    Code:
    a_string.erase(0,a_string.find_first_not_of(' '));
    Last edited by Darryl; 07-28-2005 at 01:28 PM.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Swoopy's Idea can be simplified even more
    Darryl, and your code is also more readable. The erase() makes it obvious what's happening.

  5. #5
    Banned
    Join Date
    Jun 2005
    Posts
    594
    you could use string stream;

    [URL=http://www.cplusplus.com/ref/iostream/stringstream/stringstream.html[/URL]


    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
    	string mystring = ("           Hel lo            ");
    	string mystring2;
    	stringstream ss(stringstream::in | stringstream::out);
    	ss << mystring;
    	while(ss >> mystring2)
    	{
    		cout << mystring2 << endl;
    	}
    	cin.get();
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM