代码如下:
#include <stdio.h>
int is_blank( int ch );
void deblank( char string[] );
int main()
{
char string[] = " zhang lei g";
printf( "%s \n", string );
deblank( string );
printf( "%s \n", string);
return 0;
}
void deblank( char string[])
{
char *str_temp = string;
char *str_src = string;
int IS_last_blank = 0;
#if 0
while( *str_src != '\0' )
{
if( is_blank(*str_src) == 0 )
{
strtemp++;
IS_last_blank = 0;
}
else
{
if( !is_last_blank )
{
*strtemp++ = ' ';
is_last_blank = 1;
}
}
str_src++;
}
#endif
while ( *str_src != '\0' )
{
if( is_blank(*str_src) )
{
if( !IS_last_blank )
{
*str_temp++ = ' ';
IS_last_blank = 1;
}
}
else
{
*str_temp++ = *str_src;
IS_last_blank = 0;
}
str_src++;
}
*str_temp = '\0';
}
int is_blank( int ch )
{
return ch == ' ' || ch == '\r' || ch == '\v' || ch == '\t' || ch == '\n' || ch == '\f' ;
}
C和指针答案上代码如下:
/*
** Shrink runs of white space in the given string to a single space.
*/
#define NUL
’\0’
void
deblank( char *string )
{
char
*dest;
char
*src;
int
ch;
/*
** Set source and destination pointers to beginning of the string, then
** move to 2nd character in string.
*/
src = string;
dest = string++;
/*
** Examine each character from the source string.
*/
while( (ch = *src++) != NUL ){
if( is_white( ch ) ){
/*
** We found white space. If we’re at the beginning of
** the string OR the previous char in the dest is not
** white space, store a blank.
*/
if( src == string || !is_white( dest[–1] ) )
*dest++ = ’ ’;
}
else {
/*
** Not white space: just store it.
*/
*dest++ = ch;
}
}
*dest = NUL;
}
int
is_white( int ch )
{
return ch == ’ ’ || ch == ’\t’ || ch == ’\v’ || ch == ’\f’ || ch == ’\n’|| ch == ’\r’;
}