Member Avatar for Sam R.

This is a code for removing spaces from a string, I've been asked to do this without using any standard library functions like isspace or '\b'. I've been trying for a lot of time but it always gives the same error

Error : Cannot convert 'char' to "char *"

Here is the code :

  void string :: rem_spc()
   {
     int i,j,l;
     l  = strlen(str);
     for(i=0; str[i]!='\0';i++)
      {
    if(str[i] == " ")
       str[i] = str[i+1];

      }
     for(i = 0; i<l; i++)
      {
    cout<<str[i];
      }
   }

" " indicates a string of characters, aka. char * where as each individual element is a char. To indicate a single character, use ' ' (apostrophe)

What Ktsuekiame said, plus this:

in your first loop, you are only moving the next element to the space. You need top move ALL of the data one character toward the head of the string, not just one. This requires another loop inside the first one. I think your teacher is trying to instruct you on nested loops... :-)

You need top move ALL of the data one character toward the head of the string, not just one. This requires another loop inside the first one. I think your teacher is trying to instruct you on nested loops...

std::remove() is O(N)

void remove_space( char* cstr )
{
    int next = 0 ; // position of next non-space char

    for( int i = 0 ; cstr[i] != 0 ; ++i ) // for every char till the null char
        if( cstr[i] != ' ' ) cstr[ next++ ] = cstr[i] ;

    cstr[next] = 0 ; // null terminate
}

Actually, to modify my earlier post, rather than a loop, you can use the C "strcpy()" or "memmove()" functions instead, eliminating the inner loop. It will also be faster, especially since x86 processors have very efficient string handling primitives that gcc (or Visual Studio) will hopefully utilize.

Member Avatar for Sam R.

@Ketsuekiame , @rubberman and @vijayan121 we have to do this without the use of pointers with just nesting loops, is there any way?

Here you go, this program uses the string library from c++. It will remove all the spaces from a string:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string my_str_with_spaces = "T h i s is a weird s t r . . . ";
    string without_spaces;

    for(int i = 0; i < my_str_with_spaces.size(); i++)
    {
        if(my_str_with_spaces[i] != ' ')
            without_spaces += my_str_with_spaces[i];
    }

    cout<<without_spaces<<endl;
    cin.get();
}
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.