Any tips as to how to take a string input and return a copy of the string without the blanks?
Printable View
Any tips as to how to take a string input and return a copy of the string without the blanks?
Setup a char pointer to your string, and then use
to determine whether you are pointing at white space or not.Code:isspace()
Then either move the pointer along to the next element, or add the pointer value to another array depending on the result of isspace.
Code:
p = array;
while ( *p != '\0' )
{
if ( isspace(*p) )
{
++p;
}
else
{
newarray[i++] = *p;
++p;
}
}
how come this doesn't work for me?
Code:#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXSIZE 80
int main()
{
char array[MAXSIZE];
int i = 0;
int size;
printf("Enter a string: ");
fgets(array, MAXSIZE, stdin);
size = sizeof(array);
while(i < size)
{
if( isspace(array[i]) )
{
size--;
}
else
{
printf("%c", array[i]);
}
i++;
}
return 0;
}
Works for me.Quote:
Originally Posted by mapunk
Except the fact that your loop will not terminate when it hits the end of your string.
dont listen to me im a noob
Yeah, it took out all the spaces/tabs and what not, but it was getting a bunch of other random data from other parts of the memory (which is b/c its not terminating when it should) But, I thought thats what the size-- would do, b/c it decrements the size, so every time it takes a space out it should do one less loop of the while loopQuote:
Originally Posted by jamie85
Code:while ( array[i] )
{
if ( !isspace(array[i]) )
{
putchar(array[i]);
}
i++;
}
lol, thanks...don't know why i didn't think of thatQuote:
Originally Posted by Dave_Sinkula