1. 程式人生 > >C語言去除空格方法

C語言去除空格方法

去出字串中所有的空格

char *del_all_space( char *buf )
{
	char **fields, *tmp, *final;
	int len, i, total=0, k=0, tmp_len;
	if( !buf )
		return NULL;
	len = strlen( buf );
	final = (char *)malloc(len);
	if( !final )
		return NULL;
	memset( final, 0, len );
	fields = (char **)malloc(len*sizeof(char *));
	if( !fields )
		return NULL;
	tmp = buf;
	for( i=0; i<len; i++ )
	{
		if( buf[i] == ' ' )
		{

			tmp_len = buf+i-tmp;
			fields[k] = (char *)malloc(tmp_len+sizeof(int)+1);
			if( !fields[k] )
				return NULL;
			memset( fields[k], 0, tmp_len+sizeof(int)+1 );
			memcpy( (int *)fields[k], &tmp_len, sizeof(int) );
			memcpy( fields[k]+sizeof(int), tmp, tmp_len );
			tmp = buf+i+1;
			k++;
		}
	}
	tmp_len = buf+len-tmp;
	fields[k] = (char *)malloc(tmp_len+sizeof(int)+1);
	if( !fields[k] )
		return NULL;
	memset( fields[k], 0, tmp_len+sizeof(int)+1 );
	memcpy( (int *)fields[k], &tmp_len, sizeof(int) );
	memcpy( fields[k++]+sizeof(int), tmp, tmp_len );
	tmp = final;
	for( i=0; i<k; i++ )
	{
		if( fields[i] )
		{
			tmp_len = *((int *)fields[i]);
			memcpy( tmp, fields[i]+sizeof(int), tmp_len );
			tmp += tmp_len;
			free( fields[i] );
		}
	}
	free( fields );
	return final;
}

c

int main(int argc, char **argv)
{
	char *p;
	p = del_all_space("There is a log!");
	printf( "%s\n", p?p:"NULL" );
	free(p);
	return 0;
}