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.

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.

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!

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 in the real world? :?:

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 in Problem Solving with C++ by W. Savitch, p. 493. I'm trying to figure it out too.

j

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

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

Or in one step :D

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;
}

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!!

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 the isspace() function with one of your choosing.

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

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

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.

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:

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

Yep.

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

Yep.

Wanna bet? :icon_wink:

Well, I am reading it again, because I am still trying to remove spaces from a file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.