문자열 의 빈 칸 삭제

코드 는 다음 과 같 습 니 다:
#include <stdio.h>

int is_blank( int ch );
void deblank( char string[] );

int main()
{
	char string[] = "  zhang     lei  g";
    printf( "%s 
", string ); deblank( string ); printf( "%s
", 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 == '
' || 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 == ’
’|| ch == ’\r’; }

좋은 웹페이지 즐겨찾기