How can I skip about \t and \n and all the another special chars of white-spaces in c?

Viewed 54

Given string like: ab \t \nc how can i ignore the white-spaces and to get abc in c?
I know how to skip about really tab and white-space:

if(str[i] == ' ' || str[i] = '\t')

but if I pass string that with \t strictly, so i will get str[i]=\ and str[i+1]=t. So how can I catch these cases?

For example:

char* str = "abcd \n \t ef   ";
char* str_clear = filter(str); // need to be "abcdef".

And I asking about how to write the filter function (like that i write above, i know how skip about ' ' and '' , but how can I catch "\n" and "\t"?)

1 Answers

The second part of the condition in the OP uses = where == is (apparently) intended.

Here ya go...

if(str[i] == ' ' || str[i] == '\t' || ( str[i] == '\\' && str[i+1] == 't' ) )

Better:

#include <ctype.h> // use this

if( isspace( str[i] )
|| ( str[i] == '\\' && ( str[i+1] == 't' || str[i+1] == 'n' ) ) )

Can't really see the use for this, but the OP clearly says this is wanted.

It's a string, so "sniffing" the next character is allowed. Worst case the next character is '\0'.

If the source string is being compacted into another buffer;

if( isspace( str[i] ) )
    i++; // ignore one character
else if( str[i] == '\\' && ( str[i+1] == 't' || str[i+1] == 'n' ) )
    i += 2; // ignore two characters
else
    dst[ j++ ] = str[ i++ ];
Related