954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

removing spaces from a string

Is there a function to remove spaces from a string? I need a way to have a user input a string with spaces, numbers, and letters and remove all spaces before storing it. Using scanf, cin, gets or fgets, apparently I only retain whatever is before the first space.

veronicak5678
Light Poster
37 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

scanf() and cin tokenize on whitespace, so yes, they stop reading input at any whitespace. Please don't use gets(). fgets() reads an entire line (it even returns the newline character at the end of the line), so if there are spaces in the line you'll get them too. The C++ equivalent is getline():
string s; getline( cin, s );
Except getline() doesn't leave the newline in the string.

There's no standard function to simply remove whitespace. (Are you thinking of things along the lines of removing leading and trailing whitespace, or do you also want to get rid of internal whitespace?)

If you are using C++, I suggest you check out the Boost String Algorithms Library . It has some stuff that might help.

Otherwise, you'll have to write your own function.

Hope this helps.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

Yeah, I wanted to remove internal spaces as well. I think I am almost done writing a function for it, I just couldn't believe there wasn't one already. Thanks for your help!

veronicak5678
Light Poster
37 posts since Sep 2007
Reputation Points: 10
Solved Threads: 0
 
I just couldn't believe there wasn't one already.


I'm curious. Why would you think there's a function to remove spaces from a string? Of what use would such a function be inthe real world? :?:

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
I'm curious. Why would you think there's a function to remove spaces from a string? Of what use would such a function be in the real world? :?:

It's a homework question inProblem Solving with C++ by W. Savitch, p. 493. I'm trying to figure it out too.

j

powerof2
Newbie Poster
1 post since Oct 2008
Reputation Points: 10
Solved Threads: 0
 
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

You can break the logic down into a 3 step process:
Im leaving the coding upto you.
1) Remove leading white spaces using a loop until you hit a non white space
2) Use a loop to remove the middle white spaces and copy characters into a temp array
3) Remove trailing white space by adding NULL

Im going to assume your string is fairly small and you can create a temporary array. Otherwise your going to need to be a little creative :P

kenji
Junior Poster
145 posts since May 2008
Reputation Points: 11
Solved Threads: 11
 

Or do it in one step:

For each char in str:
      If it's a space:
         * Remember that you saw a space, but don't
            copy it to the output string.
      Else (if it's not a space):
         * If it's not leading space:
            * Copy a space to the output string if
               any spaces were seen.
         * Copy the non-space char to the output string.
   Terminate output string.

Note that leading and trailing spaces are removed completely (not replaced with a single space).

nucleon
Posting Pro in Training
478 posts since Oct 2008
Reputation Points: 163
Solved Threads: 91
 

Or in one step :D

kenji
Junior Poster
145 posts since May 2008
Reputation Points: 11
Solved Threads: 11
 

Or... Use the power the string class itself to remove the spaces. I like to create classes which consolidate similar and useful tasks. StringTools is a collection of such tasks. This method removes all spaces, leading, trailing, or otherwise. It leaves formatting characters in place (like tab, newline, etc.) You can easily write another method that removes those if you need to remove them.

And "WaltP" - there are plenty instances in the RW for this method....

string StringTools::removeSpaces( string stringIn )
{
string::size_type pos = 0;
bool spacesLeft = true;

while( spacesLeft )
{
pos = stringIn.find(" ");
if( pos != string::npos )
stringIn.erase( pos, 1 );
else
spacesLeft = false;
}

return stringIn;
}

cheldric
Newbie Poster
1 post since Apr 2008
Reputation Points: 10
Solved Threads: 0
 

I don't know any function that can do that but you can write your own like this!!

#include<iostream>
#include<string>
#include<iomanip>
#include<algorithm>
using namespace std;

string urwelcome(string input)
{
	begining:

	for(unsigned int i = 0; i <= input.length(); i++)
	{
		if(input[i] == ' ')
		{
			input.erase(i, 1);
			goto begining;
		}
	}
	return input;
}

int main()
{
	string input;

	getline(cin, input);

	input = urwelcome(input);

	cout << input << endl;

	return 0;
}


i don't know exactly why I did the goto begining thing but I remember getting help here with a problem where not all the spaces get removed. I just typed it without even knowing why....so don't ask me why. Good luck finding a function that can do this and if you do please post it here!!

djextreme5
Junior Poster
104 posts since Mar 2009
Reputation Points: 76
Solved Threads: 6
 

Sigh.

#include <algorithm>   // remove_if()
#include <cctype>      // isspace()
#include <functional>  // ptr_fun <>
#include <iostream>    // I/O
#include <string>      // string
using namespace std;

int main()
  {
  cout << "Space remover.\n\n"

          "Please enter strings with spaces.\n"
          "Enter a blank line to quit.\n\n"

          "> "
       << flush;

  string s;
  while (getline( cin, s ) && !s.empty())
    {
    s.erase(
      remove_if(
        s.begin(),
        s.end(),
        ptr_fun <int, int> ( isspace )
        ),
      s.end()
      );
    cout << s << endl << string( s.length(), '-' ) << endl;

    cout << "\n> " << flush;    
    }

  cout << "Bye.\n";
  return 0;
  }


See lines 21 through 28. Replace theisspace() function with one of your choosing.

Is this thread one of those that is going to be resurrected once a year forever more?

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

str.erase (std::remove (str.begin(), str.end(), ' '), str.end());

damnpoet
Light Poster
36 posts since Feb 2010
Reputation Points: 10
Solved Threads: 7
 

One algorithm candidate is:
input =
[h][e][l][l][o][ ][w][o][r][l][d]

for each char c in input
if c is a space
then shift the contents to the left, removing the space.

Of course it would probably be more efficient to copy the array, assuming it is of a manageable size.

pseudorandom21
Practically a Posting Shark
890 posts since Jan 2011
Reputation Points: 216
Solved Threads: 111
 

All your suggestions are appreciated, but this thread is 3,5 years old. The original poster is probably no longer interested in it. :icon_smile:

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 
Is this thread one of those that is going to be resurrected once a year forever more?


Yep.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 
Is this thread one of those that is going to be resurrected once a year forever more?
Yep.


Wanna bet? :icon_wink:

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You