i need help removing spaces from a string..how do i go about this?? i have to report back the number of spaces too but ive been able to do that

thnx

(i dont want to use any of the string functions in the string library)

#include <iostream>

int stripspaces(char *str);

using namespace std;

int main()
{
	char ar[100];

	cout<<"Enter a sentence and I will strip out the spaces:"<<endl;

	cin.getline(ar, 99);

	cout<<"Your sentence without spaces is "<<stripspaces(ar)<<endl;



	return 0;
}

int stripspaces(char *str)
{

	int spacecounter = 0;

	char *p= str;

	while(*p)
	{
		if(*p == ' ')
		{	

                                     //dont know how to set this up for removing spaces

			spacecounter++;	
		}


		p++;	
	}



	return spacecounter;

}

Recommended Answers

All 33 Replies

i tried looking at your solution but dint really understand..could u plz explain

thnx

int main() {
   uint64 cycle_timer_beg;
   uint64 cycle_timer_end;

   cycle_timer_beg = GetCycleCount();

   for (int j = 0; j < 10000; ++j) {

      char arr[] = "abc     def";
      char temp[sizeof arr];
      int temp_index = 0;
      for (int i = 0; arr[i]; ++i) {
         if (arr[i] != ' ') {
            temp[temp_index++] = arr[i];
         }
      }
      temp[temp_index] = '\0';
      strcpy_s(arr, sizeof(arr), temp);

   }

   cycle_timer_end = GetCycleCount();

   cout << "Average cycle count: " << ((cycle_timer_end - cycle_timer_beg) / 10000);
   cin.ignore();
   return 0;
}

ok..i think i have an idea but im having a problem with the bold part..i know i cant do that but how can i correct it??

#include <iostream>

int stripspaces(char *str);

void printwithoutspace(char *str);

using namespace std;

int main()
{
	char ar[100];
	
	cout<<"Enter a sentence and I will strip out the spaces:"<<endl;
	
	cin.getline(ar, 99);

	return 0;
}

int stripspaces(char *str)
{

	int spacecounter = 0;
	
	char *p= str;

	while(*p)
	{
		if(*p == ' ')
		{		
			spacecounter++;	
		}


		p++;	
	}

	[B]char ar[] = str;[/B]
	for (int i = 0; ar[i]; i++) 
	{
         if (ar[i] != ' ') 
		 {
            char strA[99];

			strcpy(strA, str);

			cout<<"Your sentence without spaces is "<<strA<<endl;

         }
    }

	return spacecounter;

}

ok i fixed that but now ive got another issue my loop..cant seem to locate the problem...plz help

#include <iostream>

int stripspaces(char *str, char ar2[]);

using namespace std;

int main()
{
	char ar[100];
	
	cout<<"Enter a sentence and I will strip out the spaces:"<<endl;
	
	cin.getline(ar, 99);

	cout<<"Your sentence has "<<stripspaces(ar, ar)<<" spaces"<<endl;


	return 0;
}

int stripspaces(char *str, char ar2[])
{

	int spacecounter = 0;
	
	char *p= str;

	while(*p)
	{
		if(*p == ' ')
		{		
			spacecounter++;	
		}


		p++;	
	}


	[B]for (int i = 0; ar2[i] != ' '; i++) 
	{
            char strA[99];

			strcpy_s(strA, str);

			cout<<"Your sentence without spaces is "<<strA<<endl;

         
    }[/B]
	return spacecounter;
}
for (int i = 0; ar2[i] != ' '; i++) 
	{
            char strA[99];
	     strcpy_s(strA, str);
             cout<<"Your sentence without spaces is "<<strA<<endl;         
        }

Line 1 - That loop condition won't work. It stops your loop at the first blank.
Line 3 - Array declaration needs to come BEFORE the loop starts. You just keep creating and deleting the array if it's inside the loop.
Line 4 - What exactly are you trying to do with strcpy?
Line 5 - cout statement should come AFTER the loop when the loop is all done.

Note that you don't use the variable i at all in the loop here. I also see THREE arrays here (str, strA, and ar2). Do you want/need all three of them? If so, why? Two is plenty and it could even be done with one if you wanted to. But stick with two. It's probably easier. But I can't think of any reason you'd want three. Let's say you decide to keep str and ar2.

You need to think about exactly what you want str and ar2 to contain after this loop is done. What do each contain BEFORE the loop is started. You need to be very clear on this before designing the loop. Keep in mind that right now, since you passed the function the same argument, they are actually pointing to the same thing.

Also ask yourself whether you really want this function to take two arguments, and if so, what do they represent?

well i tried doing it with 1 argument but didnt know how to set something in my function equal to the string..apart from the pointer.

or lets just say this how can i do this with 1 argument?

well i tried doing it with 1 argument but didnt know how to set something in my function equal to the string..apart from the pointer.

or lets just say this how can i do this with 1 argument?

int stripspaces(char *str)
// str contains full string when it is passed to the function.
// str contains string without whitespace when function is done.

It can be done both with or without creating a temporary array. It's probably easier using the second array, so create a second char array called temp and copy str into it. Go through temp one character at a time. Keep track of how many non-blank characters you run into in temp. Start at the front of the str array (ie. str[0]). When you hit a non-blank, copy that character to str and increment the non-blank characters counter, which keeps track of what index of str to copy the next non-blank-character of temp to. When you've gone all the way though temp, add a null terminator to str.

#include <iostream>

int stripspaces(char *);

using namespace std;

int main()
{
    char ar[100];

    cout<<"Enter a sentence and I will strip out the spaces: ";
    cin.getline(ar,100);

    cout<<"No of spaces: "<<stripspaces(ar)
           <<"\nYour sentence without spaces is \n\t"<<ar;

    return 0;
}

int stripspaces(char *str)
{
    int spacecounter = 0;

    char *p= str;

    int &shift_factor=spacecounter; //just for understanding 

    for(; *p!='\0'; p++)
    {
        if(*p == ' ') spacecounter++;
        else if(shift_factor!=0) *(p-shift_factor)=*p; //spacecounter can be used in place      
    }

this here is broken but i think i am just mishandling the pointers. but the overall logic should get done what u need.

#include <iostream>

void stripspaces(char *, char *);

using namespace std;

int main()
{
    char ar[100];
    char *stringwithoutspaces=0;

    cout<<"Enter a sentence and I will strip out the spaces:"<<endl;
    cin.getline(ar, 99);
    stripspaces(&ar[0], stringwithoutspaces);

    cout<<"Your sentence without spaces is ";
    while(stringwithoutspaces!= 0)
    {   cout << &stringwithoutspaces[0];
        *stringwithoutspaces = *(stringwithoutspaces+1);
    }
    cout << endl;
    return 0;
}

void stripspaces(char *str, char *newp)
{

    char *p = str;

    while(*p != 0)//while *p does not point to the end of string
    {
        if (*p != ' ')//*p does not point to ' '
            newp = p; //then put *p in *newp
        else 
            *p = *(p+1); //then move *p to next item in list
    }
    return;
}

i dont know what happened to my tabs

This above code was the some thing like using the pointer arithmetics

:)

But this is the C++ forum after all, so I would suggest a C++ solution rather then a C solution.

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void StripSpaces(string);

int main()
{
    string str = "hello world with spaces";
    StripSpaces(str);
    return 0;
}

void StripSpaces(string strin)
{
    stringstream in(strin);
    stringstream out;
    string temp;
    while (in >> temp)
        out << temp;
    cout << out.str();
}

The >> operator in stringstream disregards any whitespace for you, so I took advantage of this property.
You see how clean the code looks? Hooray for c++! :)

Ps. for everone that didn't use code-tags in their reply : CLICK ME

ok no offence to others but i think im gona with vernon's for now..but thnx for the help.

im still havin problems though and hopin some1 can help me out with his way. heres what i have so far

im having a problem doing the copying part

#include <iostream>

int stripspaces(char *str, char ar2[]);

using namespace std;

int main()
{
	char ar[100];
	
	cout<<"Enter a sentence and I will strip out the spaces:"<<endl;
	
	cin.getline(ar, 99);

	cout<<"Your sentence has "<<stripspaces(ar, ar)<<" spaces"<<endl;


	return 0;
}

int stripspaces(char *str, char temp[])
{

	int spacecounter = 0;
	
	char *p= str;

	while(*p)
	{
		if(*p == ' ')
		{		
			spacecounter++;	
		}

		p++;	
	}

	return spacecounter;

	int i = 0;

	while(temp[i])
	{
		int count;

		count = 0;
[B]
		if(temp[i] != ' ')
		{

	//stuck here

			count++;
		}

		i++;
	}[/B]
	cout<<"Your string without spaces is"<<str<<endl;

}

ok no offence to others but i think im gona with vernon's for now..

Non taken. But I am curious why you choose for a C solution in a C++ program, please clarify


[edit]

im having a problem doing the copying part

What's the problem?

well as u must have noticed by now its my first time programming and im only gona need this for about another week to get through this class, till sometime from now when i may come bak to it

unfortunately as i mentioned in my original post i dont want to use any of the string library functions since i supposedly dont know those because we havent been taught them

if possible, kindly guide me to vernons approach

i pretty much dont know how to set that part up..how does it look so far though??


unfortunately as i mentioned in my original post i dont want to use any of the string library functions since i supposedly dont know those because we havent been taught them

'aight, I missed that part in your original post, sorry about that.

You still didn't tell what problems you have with your own code, but one thing I see straight away is this: return spacecounter; This breaks out of the function and the code below it will never be executed, so that might be a bit of a problem for you ;)

ill just put that at the bottom then..yeah the problem i dont know how to set it up to do the copying..i was able to implement part of his solution

int stripspaces(char *str, char temp[])
{

	int spacecounter = 0;
	
	char *p= str;

	while(*p)
	{
		if(*p == ' ')
		{		
			spacecounter++;	
		}

		p++;	
	}


	int i = 0;

	while(temp[i])
	{
		int count;

		count = 0;

		if(temp[i] != ' ')
		{

	

			count++;
		}

		i++;
	}

	cout<<"Your string without spaces is"<<str<<endl;


	return spacecounter;

}

You'll have to add something like: str[i] = temp[count]; inside your if-statement to copy the array without whitespaces.

Out of interest:

while(*p)
	{
		if(*p == ' ')
		{		
			spacecounter++;	
		}

		p++;	
	}

What's this suppose to do? Is it a requirement that you count all whitespaces? If not: delete this

[edit]
Ok it IS a requirement. I should learn to read OP better :)

yeah it is

Because I haven't been of much use to you and you figured a lot out already, here's the corrected code

int stripspaces(char str[])
{
    int spacecounter = 0;
    char *p= str;

    while(*p)
    {
        if(*p == ' ')
            spacecounter++;	
        p++;	
    }

    int i = 0;

    char temp[100]; //just big for now
    int count = 0;

    while(str[i])
    {
        if(str[i] != ' ')
        {
            temp[count] = str[i];
            count++;
        }
        i++;
    }
    cout<<"Your string without spaces is: "<<temp<<endl;
    return spacecounter;
}

You would call it like this:

int main()
{
   char str[] = "bla bla whatever";
    cout << "number of spaces" << stripspaces(str);
    return 0;
}

But it can be done better:

Do you notice that you loop through the array twice looking for spaces?? Now think for yourself how this could be improved. Hint: "else"

Also I've used a "big" array for temp at this point, but what do you think will happen if the input contains more then 100 characters? Do you know how to use malloc? (or new)

i was actually kinda close..i shouldve seen it..but thnx..wasnt quite sure i actually understood what u did but now i see it..as far as the improvement let me think about it...

no i dont know how to use those..and yeah programs gona crash..but 100s good enough

btw i tried running my code and im getting something bizarre after my sentence without space output..really strange

#include <iostream>

int stripspaces(char str[]);

using namespace std;

int main()
{
	char ar[100];
	
	cout<<"Enter a sentence and I will strip out the spaces:"<<endl;
	
	cin.getline(ar, 99);

	cout<<"Your sentence has "<<stripspaces(ar)<<" spaces"<<endl;


	return 0;
}

int stripspaces(char str[])
{
    int spacecounter = 0;
    
	char *p= str;

    while(*p)
    {
        if(*p == ' ')
            spacecounter++;	
        p++;	
    }

    int i = 0;

    char temp[100]; 
    
	int count = 0;

    while(str[i])
    {
        if(str[i] != ' ')
        {
            temp[count] = str[i];
            count++;
        }
        i++;
    }
    cout<<"Your string without spaces is: "<<temp<<endl;
    
	return spacecounter;
}

Oh duh... Where is my head today...

You'll have to terminate the string with a '\0' character. So put this: temp[count] = '\0'; just before the "cout" statement in the function. (So after the closing bracket from the while loop).

#include <iostream>

int stripspaces(char str[]);

using namespace std;

int main() {
	char ar[100];

	cout << "Enter a sentence and I will strip out the spaces:" << endl;

	cin.getline(ar, 99);

	cout << "Your sentence has " << stripspaces(ar) << " spaces" << endl;

	return 0;
}

int stripspaces(char str[]) {
	int spacecounter = 0;

	char temp[100];
	temp[0] = '\0';
	char* poss = strtok(str, " ");
	while(poss != NULL) {
		strcat(temp, poss);
		poss = strtok(NULL, " ");
		++spacecounter;
	}

	cout << "Your string without spaces is: " << temp << endl;
	return --spacecounter;
}

so am i going to have to implement all those changes or only the

temp[0] = '\0';

part; because you have written some different code after it.
and what was the problem, why do i need do this ? does it have something to do with the null terminating character?

so am i going to have to implement all those changes or only the

temp[0] = '\0';

part; because you have written some different code after it.
and what was the problem, why do i need do this ? does it have something to do with the null terminating character?

Who are you reponding to? nick or ivailosp?

ivailosp's solution doesn't work. It seems to strip the spaces fine, but it doesn't count the spaces correctly.

a        b

will have one space in ivailosp's program.

Go with the last code you posted. You need to add one line, which is the line nick suggested, after your loop and before you display the sentence.

Keep in mind that if you are supposed to RETURN the stripped code from the function, this code doesn't do that. Your returned string is unaltered. Your stripped string (temp) exists in the function only. I don't know if you are supposed to be able to use the stripped string in main or not, but if you are supposed to be able to, this code won't do it. If it doesn't matter, don't worry about it, add nick's line, and you're done.

is now ok :}

#include <iostream>

int stripspaces(char str[]);

using namespace std;

int main() {
	char ar[100];

	cout << "Enter a sentence and I will strip out the spaces:" << endl;

	cin.getline(ar, 99);

	cout << "Your sentence has " << stripspaces(ar) << " spaces" << endl;

	return 0;
}
inline int spacecnt(char strc = '\0') {
	static int cnt = 0;
	if (strc == ' ') {
		cnt++;
	}
	return cnt;
}
int stripspaces(char str[]) {
	for_each(str, str + strlen(str), spacecnt);
	char temp[100];
	temp[0] = '\0';
	char* poss = strtok(str, " ");
	while (poss != NULL) {
		strcat(temp, poss);
		poss = strtok(NULL, " ");
	}
	cout << "Your string without spaces is: " << temp << endl;
	return spacecnt();
}

yeah..thnx appreciate the help guys..but id like to understand why i have to add nick's line(i thought nick had posted the one under it sorry)

no nick original code does actually return the entire string without spaces but is just followed by some bizarre stuff

i can see what it does (that line) takes care of the garbage after i return my stripped string but what is its functionality and how am i supposed to know that?

and sorry ivailosrp i cant go with yours becuz to me ur code seems slightly more complicated and its got stuff whose functionality i just dont know..so thanks but i got to go with nick

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.