peter <> writes:
> In fact, I want to remove all NULLS and EOFs (0x1a)
> from a string then replace them all with spaces. The way I do it
> now is by using a for() loop:
>
> for(temp=0;temp<=strlen(buffer);temp++)
> {
> if(buffer[temp]== '\0' || buffer[temp]==0x1A)
> {buffer[temp]=' ';}
> }
>
> Is there a faster / more efficient way of doing this?
There's probably no faster way than a for loop, but yours can be
improved considerably by not calling strlen() on each iteration.
strlen() has to scan the entire string, and you're doing that once for
each character.
Also, the correct condition is "<", not "<=". For example if the
string's value is "hello", then strlen() returns 5, but you want to
check positions 0 through 4.
const size_t len = strlen(buffer);
for (i = 0; i < len; i ++) {
...
}
And some terminology issues. NULL is (a macro that expands to)
a null *pointer* constant; the null character is better referred
to as NUL, or just '\0'. (Yes, some character set standards do
call it NULL, but using that name can be confusing.)
And EOF is a macro that expands to a negative integer constant
expression, typically (-1). 0x1A is the control-Z character,
which is used on some systems, to indicate an end-of-file condition.
Finally, strlen() searches for the '\0' character that marks the end
of a string. If your buffer might have multiple '\0' characters in
it, then it isn't a string, and you should use some other technique
to determine how long it is (or how long the relevant portion of
it is).
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"