I need a fucntion that takes out all whitespace from a string as well as \n and \t.
I'm a newbie.
Printable View
I need a fucntion that takes out all whitespace from a string as well as \n and \t.
I'm a newbie.
Just loop through the entire array and copy anything that isn't whitespace.
Code:int i, j = 0;
char array[SIZE] = " Now is the time ",
buffer[SIZE];
for( i = 0; i < SIZE; ++i ){
if( !isspace(array[i]) ){
buffer[j] = array[i];
j++;
}
}
Won't that just make an identical copy of the original array?
1st loop-
i = 0
array[0] = ' '
so no copy...
But on the 3rd loop
i = 2
array[2] = 'N'
buffer[2] = 'N'
See what I mean?
Not anymore, thanks for pointing that out Govt.
-Prelude
Code:#include <stdio.h>
#include <stdlib.h>
void RemoveWhiteSpace(char *p);
int main(void)
{
char str[] = "Remove\t\tall white space\n and new lines";
RemoveWhiteSpace(str);
return 0;
}
void RemoveWhiteSpace(char *p)
{
char *t;
int found = 0;
while (*p)
{
if (*p == ' ' || *p == '\t' || *p == '\n')
{
t = p; // use temp pointer to move characters
while (*t)
{
*t = *(t + 1);
t++;
}
found = 1;
}
if (!found) // don't advance the pointer if we found a "filtered" character
p++;
else
found = 0;
}
}
I forgot to mention that my code will remove the whitespace from the *original* character array, where as Prelude's code will create a *new* character array.