:: Re: [DNG] [OT] [Re: Studying C as t…
Top Pagina
Delete this message
Reply to this message
Auteur: Irrwahn
Datum:  
Aan: dng
Onderwerp: Re: [DNG] [OT] [Re: Studying C as told. (For help)
On Tue, 21 Jun 2016 14:43:03 -0400, Steven W. Scott wrote:
> May as well toss in the assembler guy approach to the problem:
>
> char SpaceSquash()
> {
>           for (i = strlen(desc) - 1; i > 0; i--) {
>                if (desc[i-1] == ' ') {
>                    if (desc[i] == ' ') {
>                        strncpy(&desc[i], &desc[i+1], (strlen(desc)-i));
>                     }
>                 }
>             }
>           return 0;
> }



Assuming that was intended to be a solution to the original
problem[1]: Sorry, but you missed point.

However, it is an interesting solution to another problem,
namely that of compressing any sequence of blanks in a
string to exactly one space. Interesting insofar, as it is
very inefficient by copying the tail part of the string over
and over again. So, no cigar here either. ;o)

A more idiomatic and better performing solution to that
would be something along the lines of:

char *SpaceSquash( char *str )
{
  char *s = str, *d = str;
  while ( *s )
  {
    *d++ = *s;
    if ( *s++ == ' ' )
      while ( *s == ' ' )
        ++s;
  }
  *d = '\0';
  return str;
}



[1] K&R2 Exercise 1-9:  Write a program to copy its input 
    to its output, replacing each string of one ore more 
    blanks by a single blank.


Regards
Urban