Member Avatar for Sam R.

I need to know how to remove spaces from a string using pointers in C++. Since I'm in senior year in school I'n not used to quite complex programming. I tried doing this program but I think I'm totally hopelessly terrible wth pointers (I was out sick, the day my teacher did pointers) Can anyone help?

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<iostream.h>

void rem_spc(char *);

void main()
{
   char str[20];
   cout<<"\nEnter String :";
   gets(str);
   rem_spc(str);
   getch();
}

void rem_spc(char *t)
{
  char *str1[30];
  int i=0;
  int j=0;
   while(*t!='\0')
     {
    if(*t!=" ") // It gives an error here " cannot convert char to char* "
      *str1[i] = *t;
       t++;
       i++;
     }
     cout<<endl;
   while(*str1!='\0')
     cout<<*str1;
}

The pseudocode:

def removeSpaces (str):
    src = pointer to str
    dst = src
    while not end-of-string marker at src:
        if character at src is not space:
            set character at dst to be character at src
            increment dst
        increment src
    place end-of-string marker at dst

Below is the function to remove the spaces from char* :

static void removeSpaces (char *str) {
    // Set up two pointers.

    char *src = str;
    char *dst = src;

    // Process all characters to end of string.

    while (*src != '\0') {
        // If it's not a space, transfer and increment destination.

        if (*src != ' ')
            *dst++ = *src;

        // Increment source no matter what.

        src++;
    }

    // Terminate the new string.

    *dst = '\0';
}

Main Program :

// Test program.

int main (void)
{
    char str[] = "This is a long    string with    lots of spaces...   ";
    printf ("Old string is [%s]\n", str);
    removeSpaces (str);
    printf ("New string is [%s]\n", str);
    return 0;
}

Running this gives you:

Old string is [This is a long    string with    lots of spaces...   ]
New string is [Thisisalongstringwithlotsofspaces...]

The poster said "no pointers"... :-) Here is a function to do that without pointers at all.

// Recursive function to remove spaces from string
void removeSpc(char array[], size_t posn)
{
    for (size_t i = posn; array[i] != '\0'; i++)
    {
        if (array[i] == ' ')
        {
            // Move data up one character
            size_t j;
            for (j = i+1; array[j] != '\0'; j++)
            {
                array[j-1] = array[j];
            }
            array[j-1] = '\0';      // Move the terminator up one position.
            removeSpc(array, i);    // Make recursive call from current position.
            return;
        }
    }
}

@ rubberman

I need to know how to remove spaces from a string using pointers in C++

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.